Javascript Accessing elements in the DOM
In JavaScript, we can access the elements of the DOM (Document Object Model) using various methods. Here are some ways to access the elements in the DOM:
getElementById() method:
This method selects an element in the DOM based on the ID attribute. We can use this method as follows:
let element = document.getElementById('elementId');
getElementsByClassName() method:
This method selects an array of elements in the DOM based on the class name attribute. We can use this method as follows:
let elements = document.getElementsByClassName('className');
getElementsByTagName() method:
This method selects an array of elements in the DOM based on the tag name. We can use this method as follows:
let elements = document.getElementsByTagName('tagName');
querySelector() method:
This method selects an element in the DOM based on the CSS selector. We can use this method as follows:
let element = document.querySelector('CSSSelector');
querySelectorAll() method:
This method selects an array of elements in the DOM based on the CSS selector. We can use this method as follows:
let elements = document.querySelectorAll('CSSSelector');
Once we have accessed the element(s) using any of the above methods, we can manipulate them by changing their properties, adding or removing classes, adding or removing attributes, etc.