DEV Community

Cover image for JavaScript DOM: The Backbone of Interactive Web Applications
Karthick (k)
Karthick (k)

Posted on

JavaScript DOM: The Backbone of Interactive Web Applications

Exploring JavaScript: Understanding addEventListener and textContent

In my recent exploration of web development, I delved into the fascinating world of JavaScript, particularly the use of addEventListener and textContent. I designed a simple HTML page to demonstrate these concepts, and I wanted to share my findings and the code with you all.

The Code

Here's the HTML structure I've created:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Button link</title>
</head>

<body>
    <h1 id="mytext">Welcome to Html</h1>
    <h3 id="mytext-1">welcome to DOM</h3>

    <button id="myBtn">submit</button>

    <script>
        let text_new = document.getElementById('mytext');
        let text_new_two = document.getElementById('mytext-1');
        let button_values = document.getElementById('myBtn');
        let count = 0;

        button_values.addEventListener("click", function () {
            count = count + 1;

            if (count === 1) {
                text_new.textContent = "Welcome to Javascript Roadmap";
                text_new_two.textContent = "Welcome to DOM Roadmap";
            } else {
                count = 0;
                text_new.textContent = "Welcome to HTML";
                text_new_two.textContent = "Welcome to DOM";
            }
        });
    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Explanation

  1. HTML Structure:

    • The code starts with a simple HTML structure including two header tags (<h1> and <h3>) and a button. The headers display some introductory text.
  2. JavaScript Functionality:

    • I used JavaScript to add interactivity. With the addEventListener method, I attached a click event to the button.
    • The click event toggles the content of the headers between two states. The first click changes the text to welcome messages related to JavaScript and the DOM roadmap. A subsequent click resets the text back to the original messages.
  3. Understanding addEventListener:

    • This method is essential for handling events in JavaScript. It allows us to execute a function whenever a specified event occurs (in this case, a click event).
  4. Using textContent:

    • The textContent property sets or returns the text content of the specified node and its descendants. It allows us to dynamically change the text displayed in our HTML elements based on interaction.

Conclusion

Through this simple example, I've gained a deeper understanding of event handling in JavaScript and how we can dynamically manipulate the Document Object Model (DOM). The addEventListener and textContent features empower developers to create engaging and interactive web applications.

Happy coding!

Top comments (0)