learn2kode.in

JavaScript Selecting Elements

Selecting elements is one of the most important skills in JavaScript DOM manipulation. Before you can change text, styles, or add events, you must first select the HTML element you want to work with.
JavaScript provides several methods to select elements from the DOM. In this lesson, we will focus on the most commonly used and beginner-friendly methods.

Why Do We Select Elements?

Selecting elements allows JavaScript to:
Without selecting elements, JavaScript cannot interact with HTML.
getElementById()
The getElementById() method selects an element using its id attribute.
Syntax
document.getElementById("elementId");
Example HTML
<h1 id="title">Welcome to Learn2Kode</h1>
JavaScript Example
const heading = document.getElementById("title");
console.log(heading.textContent);
Key Points
querySelector()
The querySelector() method selects the first matching element using CSS selectors.
Syntax
document.querySelector("selector");
Example HTML
<p class="intro">JavaScript is powerful</p>
JavaScript Example
<p class="intro">JavaScript is powerful</p>
Supported Selectors
Example:
document.querySelector("#title");
document.querySelector(".box");
document.querySelector("p");
getElementById() vs querySelector()
// Access an element by its ID
const heading = document.getElementById("main-heading");
console.log(heading.textContent);
When to Use Which?
Use getElementById() when:
Use querySelector() when:
Common Beginner Mistakes
Forgetting # for IDs in querySelector
document.querySelector("title"); // Wrong
document.querySelector("#title"); // Correct
Using getElementById() with class names
document.getElementById("box"); // Works only if box is an ID

The DOM is the backbone of interactive web pages. Understanding it is essential for any JavaScript developer, whether you are working with vanilla JS or modern frameworks.

Best Practice
For modern JavaScript:
Both methods are essential and widely used in real projects.
Best Practice

What’s Next?