Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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);
?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...