document.getElementById("child") has no properties, while the error returned by IE is like: Object Required.

">
立诚勿怠,格物致知
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

本站大部分文章为原创或编译而来,对于本站版权文章,未经许可不得用于商业目的,非商业性转载请以链接形式标注原文出处。
本站内容仅供个人学习交流,不做为任何投资、建议的参考依据,因此产生的问题需自行承担。

评论 抢沙发

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

非常感谢你的打赏,我们将继续给力提供更多优质内容!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册