Dynamic HTML Manipulation with JavaScript

Changing HTML with JavaScript

This tutorial focuses on how to manipulate HTML elements using JavaScript. It explains various methods to change the content and attributes of HTML elements dynamically.

Key Concepts

  • Document Object Model (DOM): The structure of HTML documents is represented in a tree-like format, allowing JavaScript to interact with HTML elements.
  • Selecting Elements: JavaScript provides several methods to select HTML elements for manipulation, such as:
    • document.getElementById()
    • document.getElementsByClassName()
    • document.getElementsByTagName()
    • document.querySelector()
    • document.querySelectorAll()

Changing Content

Text Content: To change only the text, use the textContent property.

document.getElementById("myElement").textContent = "Just Text";

Inner HTML: You can change the HTML content of an element using the innerHTML property.

document.getElementById("myElement").innerHTML = "New Content";

Changing Attributes

Accessing Attributes: You can also access or change attributes directly.

const img = document.getElementById("myImage");
img.src = "newImage.jpg"; // Changing the image source

Set Attribute: You can change the attributes of an element with the setAttribute() method.

document.getElementById("myImage").setAttribute("src", "newImage.jpg");

Example

Here's a simple example that demonstrates changing HTML content and attributes:

<!DOCTYPE html>
<html>
<head>
    <title>Change HTML Example</title>
</head>
<body>
    <h1 id="header">Old Header</h1>
    <img id="myImage" src="oldImage.jpg" alt="Old Image">
    <button onclick="changeContent()">Change Content</button>

    <script>
        function changeContent() {
            document.getElementById("header").innerHTML = "New Header";
            document.getElementById("myImage").setAttribute("src", "newImage.jpg");
        }
    </script>
</body>
</html>

Conclusion

Manipulating HTML elements with JavaScript is a powerful way to enhance user interaction on web pages. By learning to select elements and change their content and attributes, you can create dynamic web applications.