It's all about
connecting the dots

parentNode, childNodes, children and parentElement in JavaScript

Today I have seen a small code snippet as below:


function rolloverInit() {
    for (var i=0; i

Then I searched for introduction about the term parentNode, and found some other related terms childNodes, parentElement, and children. Here are their usages.

parentNode:
Retrives the parent object in the document hierarchy.
It conforms to the W3C standard, and is supported by all major web browsers including IE.
parentElement:
Retrieves the parent object in the object hierarchy.
It is nearly the same as parentNode except that it was invented by IE and also only supported by IE. Therefore, it's better to use parentNode rather than the parentElement in the case that you are writting a cross-browsers script.
childNodes:
Retrieves a colection of HTML Elements and TextNode objects that are direct descendants of the specified object.
It conforms to the W3C standard, and is supported by all major web broswers including IE.
children:
Retrieves a collection of DHTML Objects that are direct descendants of the object.
It is nearly the same as childNodes except that it was invented by IE and also only supported by IE. Therefore, it's better to use childNode rather than the children in the case that you are writting a cross-browsers script.

parentNode can be used one by one. And if you want to fetch the name of the corresponding node, you can employ nodeName. Here is an example:


alert(document.getElementById("child").parentNode.parentNode.nodeName);

Note that error may be returned if you place the above code snippet between the opening <head> tag and the closing <head>. This is because that all JavaScript-supported browsers will run these JavaScript code before the DOM is entirely interpreted. If you are using Firefox, the error returned is like: document.getElementById("child") has no properties, while the error returned by IE is like: Object Required.

赞(0) 打赏
版权声明:非商业用途转载请注明文章链接,商业用途转载请联系邮箱获取授权。
文章名称:《parentNode, childNodes, children and parentElement in JavaScript》
文章链接:https://www.orzzone.com/parentnode-childnodes-children-and-parentelement-in-javascript.html
商业联系:yakima.public@gmail.com
本站内容仅供个人学习交流,不做为任何投资、建议的参考依据,因此产生的问题需自行承担。

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏