DOM Selectors

Omkarpro
2 min readDec 16, 2020

DOM Selectors, as the name suggests is used to select HTML elements within a document using JavaScript. There are many ways in which you can select elements in a DOM using selectors.

  • getElementById()
  • getElementsByClassName()
  • querySelector()

All those methods are properties of the document object. So in order to use one, we should prefix those elements with the document object as,

  1. document.getElementById()
  2. document.getElementsByClassName()
  3. document.querySelector()

So , let’s Start

getElementById

Here, the selection is based on the Id name. And this seems to be similar to Class name selector but there’s a difference in how many elements this selector selects. In all the above selectors, a list of all matching elements is returned. But this selector returns only the first matched element while ignoring the remaining.

As you can see, We got <p> by ID.

getElementsByClassName

This method returns all the elements that matches the specified Class name.

  • This selector is very similar to getElementsByTagName except the selection is based on Class name and not Tag name. You can see some examples from the image above.

querySelector

This one returns the first element that matches the specified CSS selector in the document.

  • document.querySelector('#box') returns the first element that matches the CSS selector box. Remaining elements are ignored.
  • document.querySelectorAll('.boxs') returns a list of all elements that matches the specified CSS selector.

Happy coding!

--

--

Omkarpro

I am Computer Science student who is passionate about New technology