DEV Community

Cover image for Select HTML elements using JavaScript
Ali Taha Shakir
Ali Taha Shakir

Posted on • Edited on

Select HTML elements using JavaScript

If you want to make changes to the website or an app after it is loaded you need to do so by changing the elements inside the DOM.

We will go through JavaScript methods which you can use to select elements in the DOM.

document.getElementsByName()
document.getElementsByTagName()
document.getElementsByClassName()
document.querySelectorAll()
document.querySelector()
document.getElementById()

document.getElementsByName() is not used that often but it is available. Basically what it does is that it selects all the element in DOM which is assigned a name property and you specify that name property inside those parenthesis.
ref: w3schools

document.getElementsByTagName() is used to select elements by tag name, for example you can get a list of all the div’s on your HTML page using this selector.
ref: w3schools

document.getElementsByClassName() is same as .getElementsByTagName() but this time we target elements using class. You specify the class name in parenthesis and it will get all those elements which have that class property assigned to them.
ref: w3schools

document.querySelectorAll() and document.querySelector() allows you to target a specific ID, Class, or a Tag Name. The difference in .querySelectorAll() and .querySelector() is that .querySelectorAll() target all the elements in HTML which matches the ID, Class, or a Tag Name that you have specified in parenthesis. While .querySelector() only targets the first element that matches the ID, Class, or a Tag Name.
ref: w3schools
ref: w3schools

document.getElementById() perhaps on of the most used command from all the selectors targets a specific ID which you have mentioned in the parenthesis.
ref: w3schools

Conclusion
We went through total of six(6) JavaScript methods in which we have four(4) methods that returns one or more elements and two(2) methods that return single element.

If you enjoyed this post please share, and follow me on DEV.to or Twitter if you would like to know as soon as I publish a post! 🔥

Top comments (0)