Introduction:
The main theme of this article is to style the elements in javascript. We have different methods to select elements in javascript. You can also apply style on HTML elements to change the visual presentation of HTML documents dynamically using JavaScript. In the following section, we'll discuss the various methods of selecting DOM’s in JavaScript.
DOM Selectors, as the name suggests are used to select HTML elements within a document using JavaScript. There are 5 ways in which you can select elements in a DOM using selectors.
- getElementsByTagName()
- getElementsByClassName()
- getElementById()
- querySelector()
- Queryselectorall()
Also Read, Javascript hasOwnProperty
getElementsByTagName:
This returns all the elements that matches the specified TagName.
- document.getElementsByTagName('h1') returns a collection of items matching the tag name h1. And since we got only one h1 element, the list contains only one elements.
- Using [0] as index, we can access the first element in the list which is <h1 class="heading">DOM Selectors</h1>.
- document.getElementsByTagName('li') returns a list of 5 elements as we have five li tags in our page.
- And any individual element can be selected by using it’s index such as document.getElementsByTagName('li')[0].