admin管理员组文章数量:1405123
I'm trying to find all text nodes on the page using jquery. But no matter what element I select, the nodeType is always 1:
$.each($('*'), function(index, el) { console.log(el.nodeType) });
Which resulted in nothing but "1" being output in the console. And to prove there is a "text node" on the page:
$('p:first').html()
=> "
I'm text
"
$('p:first')[0].nodeType
=> 1
What am I missing here? I'm using safari 5.0.4. I get the same result in firefox 3.6.12.
Thanks.
I'm trying to find all text nodes on the page using jquery. But no matter what element I select, the nodeType is always 1:
$.each($('*'), function(index, el) { console.log(el.nodeType) });
Which resulted in nothing but "1" being output in the console. And to prove there is a "text node" on the page:
$('p:first').html()
=> "
I'm text
"
$('p:first')[0].nodeType
=> 1
What am I missing here? I'm using safari 5.0.4. I get the same result in firefox 3.6.12.
Thanks.
Share Improve this question edited Mar 13, 2011 at 18:43 user1385191 asked Mar 13, 2011 at 18:11 Binary LogicBinary Logic 2,6027 gold badges32 silver badges41 bronze badges1 Answer
Reset to default 9jQuery will only select element nodes.
$('p:first')
actually selects the first <p>
element. To access the contained text node, you would need to access firstChild
at the DOM node:
alert($('p:first')[0].nodeName) // alerts P <-- element node
alert($('p:first')[0].firstChild.nodeName) // alerts #text <-- text node
DEMO
Maybe you also have a misunderstanding: Elements containing text are not text nodes. Every element you create with tags <..>
is an element node.
Example:
<p>
Foo
<span>Bar</span>
Baz
</p>
The element node <p>
has three children: Two text nodes, containing the text Foo
and Baz
, and an element node <span>
which itself has a text node as child, containing Bar
.
本文标签: jqueryjavascript nodeType is 1 no matter whatStack Overflow
版权声明:本文标题:jquery - javascript nodeType is 1 no matter what? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744293206a2599214.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论