Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

javascript - Getting the contents of an element WITHOUT its children

I have a mild preference in solving this in pure JS, but if the jQuery version is simpler, then jQuery is fine too. Effectively the situation is like this

<span id="thisone">
 The info I want
 <span id="notthisone">
  I don't want any of this nonsense
 </span>
</span>

I effectively want to get
The info I want
but not
The info I want I don't want any of this nonsense
and I especially don't want
The info I want <span id="notthisone"> I don't want any of this nonsense </span>
which is unfortunately what I am getting right now...

How would I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With js only:

Try it out: http://jsfiddle.net/g4tRn/

var result = document.getElementById('thisone').firstChild.nodeValue;    

?alert(result);?

With jQuery:

Try it out: http://jsfiddle.net/g4tRn/1

var result = $('#thisone').contents().first().text();  

alert(result);?

Bonus:

If there are other text nodes in the outer <span> that you want to get, you could do something like this:

Try it out: http://jsfiddle.net/g4tRn/4

var nodes = document.getElementById('thisone').childNodes;
var result = '';

for(var i = 0; i < nodes.length; i++) {
    if(nodes[i].nodeType == 3) {       // If it is a text node,
        result += nodes[i].nodeValue;  //    add its text to the result
    }
}

alert(result);
?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...