How to select HTML Elements in JavaScript.

In this blog post, we will see the most common ways to select HTML elements using JavaScript.

To add functionality to Html first we need to get all the required elements in our JavaScript file.

  • Selecting Elements by ID

getElementById() : getElementById() is a JavaScript DOM method. It accepts the HTML element ID and returns the element if the matching element was found, NULL if no matching element was found in the document.

syntax:

var element = document.getElementById('ID')

  • Selecting Elements by Class Name

getElementsByClassName: This is one of the JavaScript DOM method. selects all the elements having specific class names. This method returns an array-like object of all child elements which have all of the given class names.

syntax:

var element = document.getElementsByClassName('class-name)

  • Selecting Elements by Tag Name

getElementsByTagName(): This method also returns an array-like object of all child elements which have all of the given class names.

syntax:

var element = document.getElementsByTagName("h1")

var element = document.getElementsByTagName("p")

  • Selecting Elements by querySelector

querySelector: The querySelector() method only returns the first element that matches the specified selectors.

syntax:

var element = document.querySelector('.class-name')
OR

var element = document.querySelector('#ID')

  • Selecting Elements by querySelectorAll

querySelectorAll: The querySelectorAll() method returns all element that matches specified CSS selector in the document.

syntax:

var element = document.querySelectorAll('.class-name')
OR

var element = document.querySelectorAll('#ID')