Selecting Elements
querySelector()
Used to select ONE element.
It always returns the first matching element.
Real World Usage
Suppose you have:
<button class="menu-btn">
Menu
</button>
When user clicks menu button:
const menuBtn =
document.querySelector(".menu-btn");
Now JavaScript can control it.
querySelectorAll()
Used when multiple elements need to be selected.
Example
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
const cards =
document.querySelectorAll(".card");
Now all cards are selected.
getElementById()
Used to select an element by ID.
IDs should be unique.
Example:
<h1 id="hero-title">
Welcome
</h1>
const title =
document.getElementById("hero-title");
const heading = document.getElementById("title");
const headings = [
"Welcome",
"Learn JavaScript",
"Become a Frontend Developer"
];
let index = 0;
setInterval(() => {
heading.textContent = headings[index];
index = (index + 1) % headings.length;
}, 3000);
2. querySelector()
Selects the first matching element.
HTML
<p class="text">Paragraph 1</p> <p class="text">Paragraph 2</p>
JavaScript
const para = document.querySelector(".text");
console.log(para);
Output
<p class="text">Paragraph 1</p>
Only the first match is selected.
Using Tag Name
const heading = document.querySelector("h1");
Using ID
const heading = document.querySelector("#title");
Using Class
const heading = document.querySelector(".box");
3. querySelectorAll()
Selects all matching elements.
HTML
<li>Apple</li> <li>Orange</li> <li>Banana</li>
JavaScript
const items = document.querySelectorAll("li");
console.log(items);
Output:
Apple Orange Banana
4. textContent
Used to read or change text.
Example
<h1 id="title">
Hello
</h1>
Read:
title.textContent
Output:
Hello
Change Text
title.textContent = "Welcome";
5. innerHTML
Used to read or insert HTML.
Example
<div id="box"> </div> box.innerHTML = "<h2>Hello</h2>";
Result:
<div id="box">
<h2>Hello</h2>
</div>
1. classList.add()
Adds a class to an element.
Syntax
element.classList.add("classname");
Example
HTML
<h1 id="title">
Hello
</h1>
CSS
.active{
color:red;
}
JavaScript
const title =
document.getElementById("title");
title.classList.add("active");
Result
<h1 id="title" class="active">
Hello
</h1>
Text becomes red.
Real World Usage
Open Mobile Menu
Before
<div class="menu">
After
<div class="menu active">
menu.classList.add("active");
Menu becomes visible.