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.

Author: Yakima
关于作者:楠溪江人,出生于1991年,目前坐标上海。读书时代跳过级、保过送,工作后转过行。2013年本科毕业于北药。看书、码字、敲代码、打羽毛球是我花时间的爱好。曾在某上市药企任国际药品注册岗,现在某高新企业任前端管理岗。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据