JavaScript DOM Manipulation Series (Part - II)
Introduction
In the previous part of this blog post series, we explored the fundamentals of JavaScript DOM manipulation, delving into the techniques for selecting elements from an HTML document. With this foundation in place, we now embark on the next chapter of our journey - modifying elements.
Modifying Elements in the DOM:
Modifying elements is the art of altering the content, attributes, and styles of elements within the DOM tree. This dynamic manipulation empowers us to create responsive and interactive web applications. From adding new elements to removing existing ones, from updating text content to changing styles on the fly, the possibilities are endless.
1. Modifying Content:
innerHTML
:
It allows you to set or retrieve the HTML content inside an element.innerText
:
It's similar to innerHTML but deals with text content, ignoring any HTML tags.
Here's a simple example.
<!-- HTML -->
<p id="myParagraph">Original content</p>
<!-- JavaScript -->
<script>
// Modifying content using innerHTML
const paragraphHTML = document.getElementById('myParagraph');
paragraphHTML.innerHTML = '<strong>New content with HTML</strong>';
// Modifying content using innerText
const paragraphText = document.getElementById('myParagraph');
paragraphText.innerText = 'New content with text';
</script>
2. Modifying Attributes:
setAttribute
:
It enables the modification of HTML element attributes, such as src, href, or custom attributes.
<!-- HTML -->
<img id="myImage" src="original-image.jpg" alt="Original Image">
<!-- JavaScript -->
<script>
// Modifying attributes using setAttribute
const image = document.getElementById('myImage');
image.setAttribute('src', 'new.jpg');
image.setAttribute('alt', 'New Image');
</script>
3. Modifying Styles:
style
:
The style property provides direct access to the inline styles of an element, allowing you to change properties like color, font-size, or any other CSS style.
<!-- HTML -->
<p id="myParagraph">This is a paragraph</p>
<!-- JavaScript -->
<script>
// Modifying styles using the style property
const paragraph = document.getElementById('myParagraph');
paragraph.style.color = 'blue';
paragraph.style.fontSize = '18px';
paragraph.classList.add('highlight');
</script>
These examples showcase how to Modify Elements in the DOM using JavaScript. Experiment with these methods to dynamically update the content, attributes, and styles of your HTML elements based on user interactions or other events.
Check out next blog of this series for details about Creating and Appending Elements in the DOM using JavaScript!โ๏ธ
~HappyCoding!๐
Subscribe to my newsletter
Read articles from TheCodingCo directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by