Javascript DOM Selection Methods

Learn all the ways yoou can use JavaScript to ge a handle on HTML elements in the DOM!

There are six ways you can select HTML elements with JavaScript

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

All of these methods are properties of the document object and so these elements need to be prefixed with 'document'.

getElementById

document.getElementById("toggle");
//returns the first element with an id attribute set to toggle

querySelector

querySelector accepts perameters that are CSS selectors.

document.querySelector("section > img");
//Returns the first img element that is a direct child of a section element

Both getElementById and querySelector return just one element. Any remaining elements are ignored. But now lets look at some ways of selecting multiple elements with JavaScript.

querySelectorAll

querySelectorAll behaves just like querySelector, except, querySelector All selects multiple elements.

document.querySelectorAll("div p");
//Returns an array consisting of all the p elements that are anywhere inside of a div element
        

getElementsByClassName

document.getElementsByClassName("menu-item");
//Returns an array of all the elements with their class attribute set to 'menu-item'

getElementsByName

document.getElementByName("group1");
//Returns an array of all the elements with a name attribute holding the value 'group1'

getElementsByTagName

document.getElementByTagName("h1");
//Returns an array of all the 'h1' elements