2

I have the following HTML:

<div id="main">17.00<span>%</span></div>

I would like to select the 17.00 portion but it's not working when I use $('#id:first-child').html();. How can I select it?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Leo Zhang
  • 3,040
  • 3
  • 24
  • 38
  • Wouldn't say this is a duplicate. This question: getting a single, well specified text node, explicitly *excluding* a neighbor node's text contents. The linked [How do I select text nodes with jQuery?](http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery) is asking for *all* text node descendants, recursively. This question and the top answer solved it for me. – Joel Purra Dec 12 '13 at 18:37

2 Answers2

8

jQuery doesn't give much to work directly with text nodes, so you could do it like this:

$('#main')[0].firstChild

The [0] gets the first DOM element from the jQuery object, and uses the native firstChild property to get the text node.

To get the text content of the node, add .data or .nodeValue.

$('#main')[0].firstChild.data;      // 17.00
$('#main')[0].firstChild.nodeValue; // 17.00

An alternate way would be...

$('#main')[0].childNodes[0]
1

jQuery doesn't help much with text nodes. You can get the "17.00" text with this javascript:

var text = document.getElementById("main").firstChild.nodeValue;

If you really wanted to use jQuery (though there's no reason that I'm aware of), you could do this:

var text = $("#main").get(0).firstChild.nodeValue;

You can see it work here: http://jsfiddle.net/jfriend00/EAwCB/

jfriend00
  • 683,504
  • 96
  • 985
  • 979