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 contain1 or more
elementsHTMLElement
can containonly 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 anodeList selector function
(getElementsByClassName)linkID
selects an element using ansingle 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...