Understanding javascript DOM core ideas: nodeList vs HTMLElement objects

不羁岁月 提交于 2019-12-04 16:13:41
kevinius

So i did some research and i now have a full understanding of what objects the DOM returns when traversing the document tree. Since i didn't find any real answers on the net i'm going to give the answer to my own question, hope this helps someone else too.


Retrieving element nodes

You can retrieve element nodes via 1 of these options. This will either return a HTMLElement or a nodeList.

Methods to retrieve element nodes:

  • HTMLElement document.getElementById()
  • HTMLCollection document.getElementsByTagName()
  • nodeList document.getElementsByName()
  • nodeList document.getElementsByClassName()
  • HTMLElement document.querySelector()
  • nodeList document.querySelectorAll()

nodeList vs HTMLElement

  • nodeList can contain 1 or more elements
  • HTMLElement can contain only 1 element

They are different in the way you work with them. In the nodeList you have to use brackets [] with an index value to get to items in the list nodeList[2]. Whereas with the HTMLElement you allready work with the item itself.

Example

var linkClass = document.getElementsByClassName(".active");
var linkID = document.getElementById("id");

var parentFromLinkClass = linkClass[0].parentElement;
var parentFromLink = linkID.parentElement;

document.write(linkClass[0]); //returns the url of the link
document.write(linkID); //returns the url of the link

document.write(parentFromLinkClass); //HTMLLIElement (not a nodeList)
document.write(parentFromLink); //HTMLLIElement (not a nodeList)
  • linkClass selects elements using a nodeList selector function (getElementsByClassName)
  • linkID selects an element using an single element selector function (getElementByID)

DOM semantics

The DOM semantics have a very subtle way of telling you what type of object it will return. Remember that the type of object returned depends on the number of elements you can 'maximum' select.

  • getElementsByClassName - plural form of Element (Elements) - returns nodeList
  • getElementByID - single form or noun of Element - returns HTMLElement
  • querySelectorAll - selects 'all' - returns nodeList
  • querySelector - selects 'single' - returns HTMLElement
  • linkID.parentElement - single form or noun of Element - returns HTMLElement

I will update this answer when needed...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!