Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
JavaScript, the dynamic scripting language, and HTML DOM (Document Object Model) form a dynamic duo that empowers web developers to create interactive and responsive web pages. One of the key features of this synergy is the ability to dynamically change the HTML content on a webpage. In this article, we’ll delve into the fascinating realm of JavaScript and HTML DOM, exploring how developers can manipulate HTML elements seamlessly.
getElementById
, getElementsByClassName
, and getElementsByTagName
. Here’s an example using getElementById
: <div id="myDiv">Hello, World!</div>
<script>
var element = document.getElementById("myDiv");
element.innerHTML = "Greetings, Universe!";
</script>
In this example, the JavaScript code retrieves the element with the ID “myDiv” and changes its content to “Greetings, Universe!”
innerHTML
property is a powerful tool for manipulating the content within an HTML element. It allows you to replace the entire content of an element or add new content dynamically. Consider the following example: <p id="myParagraph">This is a paragraph.</p>
<script>
var paragraph = document.getElementById("myParagraph");
paragraph.innerHTML += " Additional text!";
</script>
In this case, the JavaScript code appends “Additional text!” to the existing content of the paragraph.
src
attribute of an image element to update the displayed image: <img id="myImage" src="old-image.jpg" alt="Old Image">
<script>
var image = document.getElementById("myImage");
image.src = "new-image.jpg";
image.alt = "New Image";
</script>
Here, the src
attribute is changed to “new-image.jpg,” and the alt
attribute is updated to “New Image.”
<div id="container"></div>
<script>
var container = document.getElementById("container");
// Create a new paragraph element
var newParagraph = document.createElement("p");
newParagraph.innerHTML = "This is a new paragraph.";
// Append the new paragraph to the container
container.appendChild(newParagraph);
// Remove the paragraph after a delay
setTimeout(function() {
container.removeChild(newParagraph);
}, 3000);
</script>
In this example, a new paragraph element is created, added to the container, and then removed after a delay of 3 seconds.
JavaScript, combined with HTML DOM, opens up a world of possibilities for developers to dynamically change HTML content, making web pages more interactive and engaging. Whether it’s updating text, modifying attributes, or adding/removing elements, the synergy between JavaScript and HTML DOM provides the tools necessary to create dynamic and responsive web applications. As you continue to explore these concepts, you’ll find countless opportunities to enhance the user experience on your websites.