如何使用jQuery选择DOM中的文本节点? [英] How to select text node in DOM using jQuery?
本文介绍了如何使用jQuery选择DOM中的文本节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下HTML:
<div id="main">17.00<span>%</span></div>
我想选择17.00
部分,但是当我使用$('#id:first-child').html();
时它不起作用.我该如何选择?
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?
推荐答案
jQuery不能直接与文本节点一起使用,因此您可以这样做:
jQuery doesn't give much to work directly with text nodes, so you could do it like this:
$('#main')[0].firstChild
[0]
从jQuery对象获取第一个DOM元素,并使用本机的firstChild
属性获取文本节点.
The [0]
gets the first DOM element from the jQuery object, and uses the native firstChild
property to get the text node.
要获取节点的文本内容,请添加.data
或.nodeValue
.
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]
这篇关于如何使用jQuery选择DOM中的文本节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文