Leo Zhang
Leo Zhang

Reputation: 3230

How to select text node in DOM using jQuery?

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?

Upvotes: 2

Views: 4183

Answers (2)

jfriend00
jfriend00

Reputation: 707148

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/

Upvotes: 1

user1106925
user1106925

Reputation:

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]

Upvotes: 8

Related Questions