Find HTML DOM Elements in JavaScript

In this post, I will introduce several ways to find HTML DOM elements in JavaScript.

querySelector methods

Document or Element methods

querySelectorAll(selectors)

  • Parameters: the selectors parameter is a valid CSS selector string.
  • Return Value: returns a static (not live) NodeList representing a list of the document’s elements that match the specified group of selectors, or an empty NodeList in case of no matches.

querySelector(selectors)

  • Parameters: the selectors parameter is a valid CSS selector string.
  • Return Value: return an Element object representing the first element in the document that matches the specified set of CSS selectors, or null is returned if there are no matches.

Find by id

document.querySelector("#test")

Find by HTML tag

document.querySelectorAll("p")

Find by class names

document.querySelectorAll("div.className1")
// or
document.querySelectorAll(".className1")

Find by attributes

// match elements contain a attribute
document.querySelectorAll("elementName[attrName]")
// match attribute value
container.querySelectorAll("elementName[attrName='attrValue']");
// attribute value start with
container.querySelectorAll("elementName[attrName^='attrValue']");
// attribute value end with
container.querySelectorAll("elementName[attrName$='attrValue']");
// attribute value contains
container.querySelectorAll("elementName[attrName*='attrValue']");

and

document.querySelectorAll("div.className1.className2");
// or
document.querySelectorAll(".className1.className2");
document.querySelectorAll("div[attr1='value1'][attr2='value2']");
// or
document.querySelectorAll("[attr1='value1'][attr2='value2']");

or

document.querySelectorAll("div.className1, div.className2");
// or
document.querySelectorAll(".className1, .className2");

Find descendants, children, siblings with tag names

// descendants
document.querySelectorAll("div span");
// the first span descendant
document.querySelectorAll("div span:nth-of-type(1)");
// children
document.querySelectorAll("div>span");
// the first child element
document.querySelectorAll("div :nth-child(1)")
// siblings
document.querySelectorAll("div~img");
// adjacent sibling
document.querySelectorAll("div+img");
  • nth-child(n) : Selects the nth child of a parent, regardless of the type of element.
  • nth-of-type(n) : Selects the nth child of a specific type within its parent.

For more information about CSS selectors, you can see the CSS selectors documentation.

Traversing match elements

const matchedElements = document.querySelectorAll("div");
matchedElements.forEach((item) => {
console.log(item.innerText)
});

Filter elements

const matchedElements = document.querySelectorAll("div");
// querySelectorAll returns a NodeList not an Array. You can convert it to an Array
Array.from(matchedElements).filter((item) => item.classList.contains('note'));
const matchedElements = document.querySelectorAll("div");
Array.prototype.filter.call(
matchedElements,
(item) => item.classList.contains('note'),
);

getElementsBy methods

Document or Element methods

getElementById(id)

  • Return value: An Element object describing the DOM element object matching the specified ID, or null if no matching element was found in the document.

getElementsByClassName(className)

  • Parameters: className a string representing the class name(s) to match; multiple class names are separated by whitespace.
  • Return value: A live HTMLCollection of found elements.

getElementsByName(nameAttrValue)

  • Parameters: nameAttrValue the value of the name attribute of the element(s) we are looking for.
  • Return value: A live NodeList collection, meaning it automatically updates as new elements with the same name are added to, or removed from, the document.

getElementsByTagName(elementName)

  • Parameters: elementName a string representing the name of the elements. The special string * represents all elements.
  • Return value: A live HTMLCollection of found elements.

Traverse elements

const testElements = document.getElementsByClassName('test');
for (let i = 0; i < testElements.length; i++) {
console.log(testElements[i].innerText)
}

Filter elements

const matchedElements = document.getElementsByTagName("div");
Array.from(matchedElements).filter((item) => item.classList.contains('yourClassName'));
const matchedElements = document.getElementsByTagName("div");
Array.prototype.filter.call(
matchedElements,
(item) => item.classList.contains('yourClassName'),
);

The closest method

closest(selector) looks for the nearest ancestor that matches the CSS-selector.

Summary

Method Searches by Call on an element Live
querySelector CSS-selector Yes -
querySelectorAll CSS-selector Yes -
getElementById id - -
getElementsByName name - Yes
getElementsByTagName tag or '*' Yes Yes
getElementsByClassName class Yes Yes

References

[1] Searching: getElement*, querySelector*

[2] Document.querySelector() - mdn

[3] Document.querySelectorAll() - mdn

[4] Document.getElementsByClassName() - mdn

[5] CSS selectors - mdn