Accessing & Modifying DOM Elements in JavaScript
Table of contents
- Accessing DOM Elements in JavaScript :
- 1. document.getElementById()
- 2. document.getElementsByClassName()
- 3. document.getElementsByTagName()
- 4. document.querySelector()
- 5. document.querySelectorAll()
- Modifying DOM Elements in JavaScript
- 1. Changing Text Content (.innerText, .textContent)
- 2. Changing HTML Content (.innerHTML)
- 3. Modifying Attributes (.setAttribute(), .getAttribute())
- 4. Changing CSS Styles (.style property)
- Conclusion
Accessing DOM Elements in JavaScript :
When working with JavaScript and the DOM, accessing elements is a fundamental task. JavaScript provides multiple methods to select elements and manipulate them dynamically.
1. document.getElementById()
What It Does:
This method selects an HTML element using its id
attribute. Since IDs are unique, this method always returns a single element.
Syntax:
var element = document.getElementById("myId");
Real-Life Examples:
Updating a Welcome Message
<h1 id="welcome">Hello, Guest!</h1> <button onclick="updateWelcome()">Login</button> <script> function updateWelcome() { document.getElementById("welcome").innerText = "Welcome, User!"; } </script>
Changing Button Text
<button id="myButton" onclick="changeText()">Click Me</button> <script> function changeText() { document.getElementById("myButton").innerText = "Clicked!"; } </script>
Highlighting an Input Field
<input type="text" id="nameInput" placeholder="Enter name"> <button onclick="highlightInput()">Highlight</button> <script> function highlightInput() { document.getElementById("nameInput").style.border = "2px solid red"; } </script>
2. document.getElementsByClassName()
What It Does:
This method selects all elements with a given class name and returns an HTMLCollection (similar to an array but lacks array methods).
Syntax:
var elements = document.getElementsByClassName("myClass");
Real-Life Examples:
Changing Multiple Paragraph Colors
<p class="text">Paragraph 1</p> <p class="text">Paragraph 2</p> <button onclick="changeColor()">Change Color</button> <script> function changeColor() { let paragraphs = document.getElementsByClassName("text"); for (let i = 0; i < paragraphs.length; i++) { paragraphs[i].style.color = "blue"; } } </script>
Toggling Visibility of Multiple Items
<div class="box">Box 1</div> <div class="box">Box 2</div> <button onclick="toggleBoxes()">Toggle Boxes</button> <script> function toggleBoxes() { let boxes = document.getElementsByClassName("box"); for (let i = 0; i < boxes.length; i++) { boxes[i].style.display = boxes[i].style.display === "none" ? "block" : "none"; } } </script>
Applying Styles to Multiple Elements
<span class="highlight">Item 1</span> <span class="highlight">Item 2</span> <script> let items = document.getElementsByClassName("highlight"); for (let i = 0; i < items.length; i++) { items[i].style.fontWeight = "bold"; } </script>
3. document.getElementsByTagName()
What It Does:
This method selects all elements with a given tag name and returns an HTMLCollection.
Syntax:
var elements = document.getElementsByTagName("tagname");
Real-Life Examples:
Counting All Links on a Page
<a href="#">Link 1</a> <a href="#">Link 2</a> <p id="linkCount"></p> <script> let links = document.getElementsByTagName("a"); document.getElementById("linkCount").innerText = "Total Links: " + links.length; </script>
Adding Borders to All Images
<img src="image1.jpg"> <img src="image2.jpg"> <script> let images = document.getElementsByTagName("img"); for (let i = 0; i < images.length; i++) { images[i].style.border = "2px solid black"; } </script>
Making All Headings Bold
<h1>Heading 1</h1> <h2>Heading 2</h2> <script> let headings = document.getElementsByTagName("h1"); for (let i = 0; i < headings.length; i++) { headings[i].style.fontWeight = "bold"; } </script>
4. document.querySelector()
What It Does:
This method selects the first element that matches a given CSS selector.
Syntax:
var element = document.querySelector("selector");
Real-Life Examples:
Changing First Paragraph Color
<p class="text">First Paragraph</p> <p class="text">Second Paragraph</p> <script> document.querySelector(".text").style.color = "red"; </script>
Selecting First Input Field and Adding Focus
<input type="text" class="input-field"> <input type="text" class="input-field"> <script> document.querySelector(".input-field").focus(); </script>
Changing Background of First Div
<div class="box">Box 1</div> <div class="box">Box 2</div> <script> document.querySelector(".box").style.background = "yellow"; </script>
5. document.querySelectorAll()
What It Does:
This method selects all elements that match a given CSS selector and returns a NodeList (which allows forEach
loop).
Syntax:
var elements = document.querySelectorAll("selector");
Real-Life Examples:
Changing Text Color of All List Items
<li>Item 1</li> <li>Item 2</li> <script> document.querySelectorAll("li").forEach(item => item.style.color = "blue"); </script>
Toggling Bold Style on Click
<p class="text">Paragraph 1</p> <p class="text">Paragraph 2</p> <script> document.querySelectorAll(".text").forEach(p => p.onclick = () => p.style.fontWeight = "bold"); </script>
Changing Background of All Buttons
<button>Button 1</button> <button>Button 2</button> <script> document.querySelectorAll("button").forEach(btn => btn.style.background = "lightblue"); </script>
Modifying DOM Elements in JavaScript
Manipulating HTML elements dynamically using JavaScript is an essential skill. Below are four common ways to modify elements in the DOM with real-life examples.
1. Changing Text Content (.innerText
, .textContent
)
What It Does:
.innerText
changes or retrieves the visible text of an element (ignores hidden text)..textContent
changes or retrieves the full text, including hidden text.
Syntax:
element.innerText = "New Text";
element.textContent = "New Content";
Real-Life Examples:
Updating a Button Label
<button id="myButton" onclick="changeText()">Click Me</button> <script> function changeText() { document.getElementById("myButton").innerText = "Clicked!"; } </script>
Displaying Character Count in a Textarea
<textarea id="myText" oninput="updateCount()"></textarea> <p id="charCount">Characters: 0</p> <script> function updateCount() { document.getElementById("charCount").innerText = "Characters: " + document.getElementById("myText").textContent.length; } </script>
Hiding and Showing a Message
<p id="message" style="display: none;">Welcome Back!</p> <button onclick="showMessage()">Show Message</button> <script> function showMessage() { document.getElementById("message").style.display = "block"; } </script>
2. Changing HTML Content (.innerHTML
)
What It Does:
.innerHTML
changes or retrieves the HTML inside an element.
Syntax:
element.innerHTML = "<b>Bold Text</b>";
Real-Life Examples:
Adding a Welcome Message
<div id="welcome"></div> <script> document.getElementById("welcome").innerHTML = "<h2>Welcome, User!</h2>"; </script>
Inserting a List Dynamically
<ul id="itemList"></ul> <script> document.getElementById("itemList").innerHTML = "<li>Item 1</li><li>Item 2</li>"; </script>
Creating a Simple Countdown Timer
<p id="countdown"></p> <script> let count = 10; let timer = setInterval(function() { document.getElementById("countdown").innerHTML = "Time Left: " + count; count--; if (count < 0) clearInterval(timer); }, 1000); </script>
3. Modifying Attributes (.setAttribute()
, .getAttribute()
)
What It Does:
.setAttribute(attr, value)
sets an attribute..getAttribute(attr)
gets an attribute's value.
Syntax:
element.setAttribute("attribute", "value");
var value = element.getAttribute("attribute");
Real-Life Examples:
Changing an Image Source
<img id="myImage" src="image1.jpg"> <button onclick="changeImage()">Change Image</button> <script> function changeImage() { document.getElementById("myImage").setAttribute("src", "image2.jpg"); } </script>
Modifying a Link Destination
<a id="myLink" href="https://example.com">Go to Example</a> <button onclick="updateLink()">Update Link</button> <script> function updateLink() { document.getElementById("myLink").setAttribute("href", "https://google.com"); } </script>
Toggling Input Fields Read-Only Mode
<input type="text" id="nameField" value="John"> <button onclick="toggleInput()">Enable/Disable</button> <script> function toggleInput() { let field = document.getElementById("nameField"); let isReadOnly = field.getAttribute("readonly"); if (isReadOnly) { field.removeAttribute("readonly"); } else { field.setAttribute("readonly", "true"); } } </script>
4. Changing CSS Styles (.style
property)
What It Does:
.style.property
changes the inline CSS of an element.
Syntax:
element.style.property = "value";
Real-Life Examples:
Changing Background Color on Button Click
<button id="colorButton" onclick="changeColor()">Change Background</button> <script> function changeColor() { document.body.style.backgroundColor = "lightblue"; } </script>
Expanding a Box on Hover
<div id="box" style="width:100px;height:100px;background:red;"></div> <script> let box = document.getElementById("box"); box.onmouseover = function() { box.style.width = "200px"; box.style.height = "200px"; }; box.onmouseout = function() { box.style.width = "100px"; box.style.height = "100px"; }; </script>
Hiding and Showing an Element
<p id="text">This is a paragraph.</p> <button onclick="toggleText()">Show/Hide</button> <script> function toggleText() { let text = document.getElementById("text"); text.style.display = text.style.display === "none" ? "block" : "none"; } </script>
Conclusion
These methods help dynamically modify content, attributes, and styles on a webpage. Practicing them will make DOM manipulation easier and more intuitive