JAVASCRIPT DOM SELECTORS

Alex Ngundji
2 min readOct 8, 2020

JavaScript is most commonly used to get or modify the content or value of the HTML elements on the page, as well as to apply some effects like show, hide, animations etc. But, before we can perform any action we need to find or select the target HTML element. DOM Selectors are useful in helping us find and target those elements.

These are 5 ways in which we can select elements in the DOM using selectors

  • querySelector()
  • querySelectorAll()
  • getElementsByTagName()
  • getElementsByClassName()
  • getElementById()

These selectors are method of the document object. Many of the methods used to access the page are found on the document object.

QuerySelector()

The querySelector() method returns the first element that matches a specified selector(s) in the document.

example:

document.querySelector(“#www-wikipedia-org”);

QuerySelectorAll()

The querySelectorAll() method returns all elements in the document that matches a specified selector(s), as a static NodeList object.

Example:

document.querySelectorAll(“#www-wikipedia-org”);

GetElementsByTagName()

The getElementsByTagName() method returns a collection of an elements’s child elements with the specified tag name, as a NodeList object.

Example:

document.getElementsByTagName(“DIV”)[0];

GetElementsByClassName()

The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as an HTMLCollection object.

Example:

 getElementsByClassName(“lang-list-button-wrapper”);

GetElementById()

The getElementById() method returns the element that has the ID attribute with the specified value.

Example:

 document.getElementById(“task”);

Overview

Here is a table overview of the five methods we have covered above

--

--