views:

75

answers:

3

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?

+9  A: 

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);
​
patrick dw
+1 Although this sorta cheats with a specialized case
pst
My answer was JQuery-specific, but I like yours better. Could replace the document.getElementById call to retain JQuery's abstraction.
richardtallent
@pst - I don't understand what you mean.
patrick dw
Beat me. Both native and jQuery. JSFiddle usage. +1 on all around.
Jason McCreary
@richardtallent - You mean like a hybrid? That's true. A little less code that way. http://jsfiddle.net/g4tRn/2/
patrick dw
+1 for JSFiddle - great example.
rockinthesixstring
@patrick you are an animal... fantastic answer!
Doug Neiner
@patrick: your first, simplest solution works perfectly for my needs. Thanks!
Mala
@Mala - You're welcome. :o)
patrick dw
@Doug - You're too kind! ;o)
patrick dw
A: 

Have you tried something like this?

var thisone = $("#thisone").clone();
thisone.children().remove();
var mytext = thisone.html();
richardtallent
`.text()` at the end, surely?
bobince
+3  A: 

If you just want the first child then it's rather simple. If you are looking for the first text-only element then this code will need some modification.

var text = document.getElementById('thisone').firstChild.nodeValue;
alert(text);
Jason McCreary