Introduction to the DOM
The Document Object Model (DOM) is a programming interface that represents an HTML document as a structured tree. Each HTML element is treated as an object, allowing JavaScript to interact with and modify the page dynamically.
When working with the DOM, we often need to select specific elements to change their content, styles, or attributes.
Two common methods for selecting elements in JavaScript:
document.getElementsByTagName()
– Selects elements by their tag name (e.g.,div
,p
,h1
).document.getElementsByClassName()
– Selects elements by their class name (e.g.,button
,highlight
).
Both methods return a live HTMLCollection
, meaning that any changes in the DOM (such as adding or removing elements) are immediately reflected in the collection.
1. getElementsByTagName()
– Selecting Elements by Tag Name
Syntax:
document.getElementsByTagName("tagName");
tagName
: The HTML tag name you want to select (e.g.,"p"
,"div"
,"h1"
).- Returns an
HTMLCollection
containing all matching elements.
Example 1: Selecting All <p>
Elements
<!DOCTYPE html>
<html>
<head>
<title>getElementsByTagName Example</title>
</head>
<body>
<h1>Heading 1</h1>
<h1>Heading 2</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<script>
// Selecting all <p> elements
let paragraphs = document.getElementsByTagName("p");
console.log(paragraphs); // Logs an HTMLCollection of <p> elements
// Changing text color of all <p> elements
for (let i = 0; i < paragraphs.length; i++) {
paragraphs[i].style.color = "blue";
}
</script>
</body>
</html>
Key Points:
✔ Returns a live collection (updates automatically when new elements are added or removed).
✔ If no elements match, it returns an empty collection, not null
.
✔ The result is an HTMLCollection
, which is not an array but can be converted into one.
✔ Elements can be accessed using indexing (collection[index]
).
Example 2: Accessing Specific Elements by Index
let headings = document.getElementsByTagName("h1");
console.log(headings[0].textContent); // Logs text of the first <h1>
Common Mistakes & Solutions
❌ Mistake 1: Treating HTMLCollection
as an Array
let items = document.getElementsByTagName("p");
items.forEach(item => console.log(item)); // ❌ TypeError: items.forEach is
not a function
✅ Solution: Convert HTMLCollection
to an Array
Array.from(items).forEach(item => console.log(item));
❌ Mistake 2: Using an Incorrect Tag Name (Case-Sensitive)
document.getElementsByTagName("P"); // ❌ Returns empty collection
✅ Solution: Always use lowercase tag names
document.getElementsByTagName("p"); // ✅ Works correctly
2. getElementsByClassName()
– Selecting Elements by Class Name
Syntax:
document.getElementsByClassName("className");
className
: The name of the CSS class you want to select.- Returns an
HTMLCollection
of elements that share the specified class.
Example 1: Selecting Elements by Class Name
<!DOCTYPE html>
<html>
<head>
<title>getElementsByClassName Example</title>
<style>
.highlight { color: red; }
</style>
</head>
<body>
<p class="highlight">This is a highlighted paragraph.</p>
<p class="highlight">Another highlighted paragraph.</p>
<p>This is a normal paragraph.</p>
<script>
// Selecting elements with class "highlight"
let highlighted = document.getElementsByClassName("highlight");
console.log(highlighted); // Logs an HTMLCollection of
elements with class 'highlight'
// Changing background color of all elements with class "highlight"
for (let i = 0; i < highlighted.length; i++) {
highlighted[i].style.backgroundColor = "yellow";
}
</script>
</body>
</html>
Key Points:
✔ Similar to getElementsByTagName()
, this method returns a live HTMLCollection
.
✔ Returns an empty collection if no matching elements are found.
✔ Multiple elements can have the same class, so the collection often contains multiple elements.
✔ Loop through the collection to modify all selected elements.
Common Mistakes & Solutions
❌ Mistake 1: Forgetting that HTMLCollection
is not an Array
let items = document.getElementsByClassName("highlight");
items.forEach(item => console.log(item)); // ❌ TypeError
✅ Solution: Convert to an Array first
Array.from(items).forEach(item => console.log(item));
❌ Mistake 2: Using Incorrect Class Name (Case-Sensitive)
document.getElementsByClassName(" Highlight "); // ❌ Returns empty collection
✅ Solution: Ensure class name matches exactly
document.getElementsByClassName("highlight"); // ✅ Correct usage
❌ Mistake 3: Forgetting That HTMLCollection
Is Live
let items = document.getElementsByClassName("highlight");
document.body.innerHTML += '<p class="highlight">New paragraph</p>';
console.log(items.length); // ✅ Updates automatically with new elements
✅ Remember that HTMLCollection
dynamically updates when new elements are added.
3. Differences Between getElementsByTagName()
& getElementsByClassName()
Feature | getElementsByTagName() |
getElementsByClassName() |
---|---|---|
Selects by | Tag name ("p" , "div" ) |
Class name ("highlight" ) |
Return type | HTMLCollection |
HTMLCollection |
Live collection? | ✅ Yes | ✅ Yes |
Case-sensitive? | ✅ Yes (lowercase) | ✅ Yes |
Can return multiple elements? | ✅ Yes | ✅ Yes |
Common use case | Selecting elements of a specific type | Selecting elements of a specific style |
4. Summary & Best Practices
✔ getElementsByTagName(tagName)
→ Selects elements by tag name, returns a live HTMLCollection
.
✔ getElementsByClassName(className)
→ Selects elements by class name, also returns a live HTMLCollection
.
✔ Both methods require loops (for
or Array.from()
) to modify multiple elements.
✔ Not an array! Convert to an array when needed using Array.from()
.
✔ Live collection: Updates automatically if elements are added/removed.
By mastering these selection methods, you’ll be able to efficiently access and manipulate elements in your JavaScript projects. 🚀
Post a Comment