While working on DOM, think of CSS where we actually doing two things that is selecting an element and applying styles or affect. Same thing applies here.
Example :
In above example, we are selecting document which is HTML with in that we have access to body element. For this body element we have access to style property. By using style property we are applying background color and text color style for the body element.
Selecting HTML Elements
We have to select HTML elements to apply styles or affects by using javascript. We can select elements in different ways.
- Selecting HTML elements by id
- Selecting HTML elements by tag name
- Selecting HTML elements by class name
- Selecting HTML elements by css
- querySelector
- querySelectorAll
Selecting HTML elements by id
By using the id of HTML element, we can select that particular HTML element.
Example :
In above example, we are selecting p element by id, if the element is found, the method will return the element as an object. if not found text will return null.
Selecting HTML elements by tag name
By using the tag name of HTML element, we can select all HTML elements which has same tag name.
Example :
In above example, we are accessing the element using index of ‘0’ because getElementsByTagName gives array-like object.
Selecting HTML elements by class name
By using class name, we can select HTML elements which has same class name. It returns list of all elements which has same class name.
Example :
Selecting HTML elements by css
We can select all HTML elements that match a specified CSS selector i.e id, class names, attributes by using querySelector or querySelectorAll.
The difference between querySelector and querySelectorAll is querySelector selects single element where as querySelectorAll selects all elements with specified CSS selector.
Here, you have to use dot notation for class, hash notation for id like selecting element in CSS. And we can select element by complicated CSS also. Check out the example.
Example :
Using querySelector
Using querySelectorAll