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.
document.body.style.backgroundColor = "blue";
document.body.style.color = "white";
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.
We have to select HTML elements to apply styles or affects by using javascript. We can select elements in different ways.
By using the id of HTML element, we can select that particular HTML element.
<p id="greet">Hello World</p>
let text = document.getElementById("greet");
console.log(text); // Prints: <p id="greet">Hello World</p>
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.
By using the tag name of HTML element, we can select all HTML elements which has same tag name.
<p>Hello World</p>
let text = document.getElementsByTagName("p");
console.log(text[0]); // Prints: <p>Hello World</p>
In above example, we are accessing the element using index of ‘0’ because getElementsByTagName gives array-like object.
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.
<p class="result">Hello World</p>
<button class="result">Click Me</button>
const select = document.getElementsByClassName("result");
console.log(select); // Prints: HTMLCollection(2) [p.result, button.result]
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.
<div class="result">
<p>Hello World</p>
<button>Click Me</button>
</div>
<div class="result">
<p>Hello There!</p>
<button>Hit Me</button>
</div>
const select = document.querySelector(".result p");
console.log(select); // Prints: <p>Hello World</p>
const select = document.querySelectorAll(".result p");
console.log(select); // Prints: NodeList(2) [p, p]