Elevate Your JavaScript Skills DOM Element Selection as Objects
Selecting Elements as Objects:
Learn how to use the Document Object Model (DOM) to access and manipulate HTML elements. Understand methods like getElementById, getElementsByClassName, getElementsByTagName, querySelector, and querySelectorAll.
Manipulating Element Content:
Explore techniques to change text content, create and append new elements dynamically, and remove elements from the document.
Styling Elements:
Dive into styling elements dynamically using JavaScript. Change background colors, fonts, and more to create a polished user interface.
Event Handling:
Master event handling by adding event listeners. Respond to user actions, like clicks, and dynamically update content for a seamless user experience.
Selecting elements as objects in JavaScript involves using the Document Object Model (DOM) to access and manipulate HTML elements on a web page. The DOM represents the structure of a document as a tree of objects, where each object corresponds to a part of the document, such as elements, attributes, and text.
To select elements as objects, you can use various methods provided by the DOM. Here are some common ways to select elements in JavaScript:
1. getElementById:
This method retrieves an element by its ID attribute.
<div id=”myElement”>Hello, World!</div>
const elementById = document.getElementById(“myElement”);
console.log(elementById.textContent); // Outputs: Hello, World!
2. getElementsByClassName:
This method returns a collection of elements with the given class name.
<p class=”myClass”>This is a paragraph.</p>
<p class=”myClass”>Another paragraph.</p>
const elementsByClass = document.getElementsByClassName(“myClass”);
console.log(elementsByClass[0].textContent); // Outputs: This is a paragraph.
3. getElementsByTagName:
This method returns a collection of elements with the given tag name.
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
const elementsByTagName = document.getElementsByTagName(“li”);
console.log(elementsByTagName[1].textContent); // Outputs: Item 2
4. querySelector:
This method returns the first element that matches a specified CSS selector.
<div class=”container”>
<p class=”content”>Hello!</p>
</div>
const elementByQuery = document.querySelector(“.container .content”);
console.log(elementByQuery.textContent); // Outputs: Hello!
5. querySelectorAll:
This method returns a NodeList of all elements that match a specified CSS selector.
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
const elementsByQueryAll = document.querySelectorAll(“li”);
elementsByQueryAll.forEach(function (element) {
console.log(element.textContent);
});
// Outputs:
// Item 1
// Item 2
These are some basic examples, and there are many other methods and techniques for selecting and manipulating elements in JavaScript. Understanding the DOM and its various methods is crucial for effective web development with JavaScript.
Coding exercises
Exercise 1: Get Element by ID
Description: Retrieve the text content of an element with the ID “myParagraph” and log it to the console.
Code Example:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Exercise 1</title>
</head>
<body>
<p id=”myParagraph”>This is a sample paragraph.</p>
<script>
// Your JavaScript code goes here
</script>
</body>
</html>
Solution:
const elementById = document.getElementById(“myParagraph”);
console.log(elementById.textContent);
Exercise 2: Get Elements by Class
Description: Retrieve the text content of all elements with the class “highlight” and log them to the console.
Code Example:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Exercise 2</title>
</head>
<body>
<p class=”highlight”>First paragraph.</p>
<p class=”highlight”>Second paragraph.</p>
<script>
// Your JavaScript code goes here
</script>
</body>
</html>
Solution:
const elementsByClass = document.getElementsByClassName(“highlight”);
for (const i = 0; i < elementsByClass.length; i++) {
console.log(elementsByClass[i].textContent);
}
Exercise 3: Get Elements by Tag Name
Description: Retrieve the text content of all “li” elements and log them to the console.
Code Example:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Exercise 3</title>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
<script>
// Your JavaScript code goes here
</script>
</body>
</html>
Solution:
const elementsByTagName = document.getElementsByTagName(“li”);
for (const i = 0; i < elementsByTagName.length; i++) {
console.log(elementsByTagName[i].textContent);
}
Exercise 4: Query Selector
Description: Retrieve the text content of the first “h2” element and log it to the console.
Code Example:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Exercise 4</title>
</head>
<body>
<div>
<h2>Heading 1</h2>
<h2>Heading 2</h2>
</div>
<script>
// Your JavaScript code goes here
</script>
</body>
</html>
Solution:
const elementByQuery = document.querySelector(“h2”);
console.log(elementByQuery.textContent);
Exercise 5: Query Selector All
Description: Retrieve the text content of all “p” elements with the class “info” and log them to the console.
Code Example:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Exercise 5</title>
</head>
<body>
<p class=”info”>Info 1</p>
<p class=”info”>Info 2</p>
<script>
// Your JavaScript code goes here
</script>
</body>
</html>
Solution:
const elementsByQueryAll = document.querySelectorAll(“p.info”);
elementsByQueryAll.forEach(function (element) {
console.log(element.textContent);
});
Exercise 6: Changing Element Content
Description: Change the text content of the element with the ID “changeMe” to “New Content.”
Code Example:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Exercise 6</title>
</head>
<body>
<p id=”changeMe”>Old Content</p>
<script>
// Your JavaScript code goes here
</script>
</body>
</html>
Solution:
const elementToChange = document.getElementById(“changeMe”);
elementToChange.textContent = “New Content”;
Exercise 7: Adding Elements
Description: Create a new “div” element, set its text content to “Dynamic Content,” and append it to the body.
Code Example:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Exercise 7</title>
</head>
<body>
<script>
// Your JavaScript code goes here
</script>
</body>
</html>
Solution:
const newDiv = document.createElement(“div”);
newDiv.textContent = “Dynamic Content”;
document.body.appendChild(newDiv);
Exercise 8: Removing Elements
Description: Remove the element with the ID “removeMe” from the document.
Code Example:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Exercise 8</title>
</head>
<body>
<p id=”removeMe”>Content to be removed</p>
<script>
// Your JavaScript code goes here
</script>
</body>
</html>
Solution:
const elementToRemove = document.getElementById(“removeMe”);
elementToRemove.parentNode.removeChild(elementToRemove);
Exercise 9: Styling Elements
Description: Change the background color of all “li” elements to “lightblue.”
Code Example:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Exercise 9</title>
<style>
li {
padding: 10px;
border: 1px solid #ccc;
margin: 5px;
}
</style>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
<script>
// Your JavaScript code goes here
</script>
</body>
</html>
Solution:
const elementsToStyle = document.querySelectorAll(“li”);
elementsToStyle.forEach(function (element) {
element.style.backgroundColor = “lightblue”;
});
Exercise 10: Event Handling
Description: Add a click event listener to the button. When clicked, change the text content of the paragraph with the ID “clickMe” to “Button Clicked!”
Code Example:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Exercise 10</title>
</head>
<body>
<button id=”myButton”>Click Me</button>
<p id=”clickMe”>Original Text</p>
<script>
// Your JavaScript code goes here
</script>
</body>
</html>
Solution:
const button = document.getElementById(“myButton”);
const paragraphToChange = document.getElementById(“clickMe”);
button.addEventListener(“click”, function () {
paragraphToChange.textContent = “Button Clicked!”;
});
These exercises cover a range of scenarios involving selecting and manipulating elements in JavaScript.
Questions:
Q1: What method is used to retrieve an element by its ID?
a) getElementByAttribute
b) getElementById
c) getElementByName
d) getElementByClass
Q2: How do you retrieve all elements with a specific class name?
a) getElementsByClass
b) getElementsByTag
c) getElementByClass
d) getElementsByClassName
Q3: Which method is used to retrieve elements by tag name?
a) getElementsByName
b) getElementById
c) getElementsByTag
d) getElementsByTagName
Q4: What does the querySelector method do?
a) Retrieves the first element that matches a specified CSS selector.
b) Retrieves all elements that match a specified CSS selector.
c) Retrieves elements by tag name.
d) Retrieves elements by class name.
Q5: How do you retrieve all elements that match a CSS selector?
a) querySelector
b) getElementById
c) querySelectorAll
d) getElementsByClassName
Q6: How can you change the text content of an element with the ID “myElement”?
a) changeText(“myElement”, “New Content”)
b) document.getElementById(“myElement”).text = “New Content”;
c) document.getElementById(“myElement”).textContent = “New Content”;
d) setText(“myElement”, “New Content”)
Q7: Which method is used to create a new HTML element?
a) createElement
b) createNode
c) newElement
d) addNode
Q8: How can you remove an element with the ID “removeMe” from the document?
a) removeElement(“removeMe”)
b) document.remove(“removeMe”)
c) document.getElementById(“removeMe”).remove()
d) removeChild(“removeMe”)
Q9: What property is used to change the background color of an element?
a) element.color
b) element.background
c) element.style.backgroundColor
d) element.bgColor
Q10: How do you add a click event listener to an element with the ID “myButton”?
a) document.getElementById(“myButton”).onClick(handleClick)
b) document.getElementById(“myButton”).addEventListener(“click”, handleClick)
c) document.getElementById(“myButton”).click(handleClick)
d) document.getElementById(“myButton”).on(“click”, handleClick)
Answers:
- Answer: b) getElementById
- Answer: d) getElementsByClassName
- Answer: d) getElementsByTagName
- Answer: a) Retrieves the first element that matches a specified CSS selector.
- Answer: c) querySelectorAll
- Answer: c) document.getElementById(“myElement”).textContent = “New Content”;
- Answer: a) createElement
- Answer: c) document.getElementById(“removeMe”).remove()
- Answer: c) element.style.backgroundColor
- Answer: b) document.getElementById(“myButton”).addEventListener(“click”, handleClick)