Selecting Elements:
*Finding HTML elements by id
*Finding HTML elements by tag name
*Finding HTML elements by class name
*Finding HTML elements by CSS selectors
i)The querySelector() Method
ii)The querySelectorAll() Method
*Finding HTML elements by HTML object collections
Finding HTML Element by Id:
The easiest way to find an HTML element in the DOM, is by using the element id.
id="user":
const element=document.getElementById("user")
Finding HTML elements by tag name:
Select from the Tag name
<P>,<span>and<a>,<h1>-<h6>etc..,
<h2>HTML</h2>
const element=document.getElementsByTagName("h2");
Finding HTML elements by class name:
Selects all elements with the same class name.
<p class="text">Apple</p>
<p class="text">Banana</p>
<script>
let element=document.getElementsByClassName("text");
<script>
The querySelector() Method:
Selects only the first element that matches a CSS selector.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML DOM</h1>
<h2>The querySelector() Method</h2>
<p class="demo"></p>
<script>
// Access a paragraph Element
const myPara = document.querySelector(".demo");
// Change the content of the Element
myPara.innerHTML = "Hello World!";
</script>
</body>
</html>
We can use
document.querySelector("#title"); // id
document.querySelector(".text"); // class name
document.querySelector("p"); // tag name
The querySelectorAll() Method:
Selects all elements that match a CSS selector.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML DOM</h1>
<h2>The querySelectorAll() Method</h2>
<p class="demo">One</p>
<p class="demo">Two</p>
<script>
// Access a paragraph Element
const myItems = document.querySelectorAll(".demo");
// Change the content of the Element
myItems[0].innerHTML = "First";
</script>
</body>
</html>
We think of a classroom:
querySelector() = Calls one student (the first one who matches).
querySelectorAll() = Calls all students who match the condition.
Top comments (0)