Element Node Selection

Selecting a Specific Element Node

The most common methods for getting a reference to a single element node are:

  • querySelector()
  • getElementById()
<div id="first">This is a DIV</div>  
var element = document.querySelector('div');  
var element1 = document.getElementById('first');  
console.log(element.textContent);//"This is a DIV"  
console.log(element1.textContent)//"This is a DIV"  

The querySelector() method permits a parameter in the form of a CSS selector syntax. Basically, you can pass this method a CSS3 selector

querySelector() will return the first node element found in the document based on the selector.

Selecting/Creating a List (NodeList) of Element Nodes

The most common methods for selecting/creating a list of nodes in an HTML document are:

  • querySelectorAll()
  • getElementsByTagName()
  • getElementsByClassName()

NodeLists created from getElementsByTagName() and getElementsByClassName() are considered live and will always reflect the state of the document, even if the document is updated after the list is created/selected.

The querySelectorAll() method does not return a live list of elements. This means the list created from querySelectorAll() is a snapshot of the document at the time it was created and does not reflect the document as it changes. The list is static, not live.

Selecting All Immediate Child Element Nodes

Using the children property from an element node, we can get a list [an HTMLCollection] of all the immediate child nodes that are element nodes.

Using children only gives us the immediate element nodes, excluding any nodes (e.g., text nodes) that are not elements. If the element has no children, children will return an empty array-like list.

Selecting Contextual Elements

The methods querySelector(), querySelectorAll(), getElementsByTagName(), and getElementsByClassName, typically accessed from the document object, are also defined on element nodes. This allows these methods to limit their results to a specific vein (or set of veins) of the DOM tree.

<li class="liClass">Hello</li>  
<li class="liClass">big</li>  
<li class="liClass">bad</li>  
<li class="liClass">world</li>  

var div = document.querySelector('div');


Preconfigured Selections/Lists of Element Nodes

  • document.all: All elements in the HTML document.

  • document.forms: All <form> elements in the HTML document

  • document.images:All <img> elements in the HTML document
  • document.links:All <a> elements in the HTML document
  • document.scripts:All <script> elements in the HTML document
  • document.styleSheets:All <link> or <style> elements in the HTML document

These preconfigured arrays are constructed from the HTMLCollection interface/object, except for document.styleSheets, which uses StyleSheetList.
HTMLCollection is live, just like NodeList [except for querySelectorAll()].