青青子衿,悠悠我心
但为君故,沉吟至今

parentNode, childNodes, children and parentElement in JavaScript

Today I have seen a small code snippet as below:

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:

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
分享到: 更多 (0)

评论 抢沙发

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

其他地方 也 能 看到我

Github豆瓣读书

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

支付宝扫一扫打赏

微信扫一扫打赏