孩子和孩子节点在JavaScript中有什么区别? [英] What is the difference between children and childNodes in JavaScript?

查看:127
本文介绍了孩子和孩子节点在JavaScript中有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己使用JavaScript,并且跨越 childNodes children 属性。我想知道他们之间有什么区别。另外还有一个是其他的?

I have found myself using JavaScript and I ran across childNodes and children properties. I am wondering what the difference between them is. Also is one preferred to the other?

推荐答案

.children ,w3.org/TR/domcore/#elementrel =noreferrer>。只有元素有孩子,这些孩子都是元素。

.children is a property of an Element. Only Elements have children, and these children are all of type Element.

然而 .childNodes Node .childNodes 可以包含任何节点。

However .childNodes is a property of Node. .childNodes can contain any node.

所以一个具体的例子是

var el = document.createElement("div");
el.textContent = "foo"
el.childNodes.length === 1; // TextNode is a node child
el.children.length === 0; // no Element children

当然 .children 是DOM4,所以浏览器支持是不稳定的,但是如果您使用 DOM-shim ,您的跨浏览器问题会消失!

Of course .children is DOM4 so browser support is shaky, however if you use the DOM-shim, your cross browser problems will go away!

大多数时候你想使用 .children ,因为一般你不想要在您的DOM操作中循环TextNodes或注释。

Most of the time you want to use .children because generally you don't want to loop over TextNodes or Comments in your DOM manipulation.

如果您想要操作TextNodes,您可能需要 .textContent 而不是。

If you do want to manipulate TextNodes you probably want .textContent instead.

这篇关于孩子和孩子节点在JavaScript中有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆