Javascript DOM and Events

Until now, we have mostly worked with JavaScript in the console. The DOM lets JavaScript work with the HTML page itself. For example, JavaScript can change text, change styles, create elements, and respond when someone clicks a button. Let’s begin with Javascript DOM and events.

What is the DOM?

DOM stands for Document Object Model. The DOM represents an HTML page in a way that JavaScript can access and change.

Suppose your HTML contains:

<h1 id="title">Hello</h1>

JavaScript can find this heading and change its text.

Selecting HTML Elements

Before changing an HTML element, JavaScript needs to find it. The most commonly used methods are:

  • getElementById()
  • querySelector()
  • querySelectorAll()

getElementById()

Use it when you want to select an element by its id.

<!DOCTYPE html>
<html>
<head>
    <title>Selecting an Element</title>
</head>
<body>

    <h1 id="title">Hello JavaScript</h1>

    <script>
        let heading = document.getElementById("title");

        console.log(heading);
    </script>

</body>
</html>

querySelector()

querySelector() selects the first element that matches a CSS selector.

let heading = document.querySelector("#title");

You can also select a class:

let box = document.querySelector(".box");

Changing HTML Content

Once you have selected an element, you can change its content. The textContent property changes the text inside an element.

<!DOCTYPE html>
<html>
<head>
    <title>Changing HTML Content</title>
</head>
<body>

    <h1 id="title">Old Heading</h1>

    <script>
        let heading = document.getElementById("title");

        heading.textContent = "New Heading";
    </script>

</body>
</html>

Output: The heading changes from Old Heading to New Heading.

You can also use innerHTML when you need to insert HTML.

heading.innerHTML = "<span>New Heading</span>";

For plain text, textContent is usually the better choice.

Changing CSS with JavaScript

JavaScript can also change the style of an element.

<!DOCTYPE html>
<html>
<head>
    <title>Changing CSS</title>
</head>
<body>

    <h1 id="title">Hello JavaScript</h1>

    <script>
        let heading = document.getElementById("title");

        heading.style.color = "blue";
        heading.style.fontSize = "40px";
    </script>

</body>
</html>

Output: The heading becomes blue and larger.

Creating Elements

JavaScript can create new HTML elements while the page is running.

<!DOCTYPE html>
<html>
<head>
    <title>Creating Elements</title>
</head>
<body>

    <div id="container"></div>

    <script>
        let paragraph = document.createElement("p");

        paragraph.textContent = "This paragraph was created with JavaScript.";

        document.getElementById("container").appendChild(paragraph);
    </script>

</body>
</html>

createElement() creates the element, while appendChild() adds it to the page.

Removing Elements

You can also remove an element from the page.

<!DOCTYPE html>
<html>
<head>
    <title>Removing Elements</title>
</head>
<body>

    <p id="message">This message will be removed.</p>

    <script>
        let message = document.getElementById("message");

        message.remove();
    </script>

</body>
</html>

Output: The paragraph is removed when the page loads.

JavaScript Events

An event is something that happens on a webpage.

For example:

  • A user clicks a button.
  • A key is pressed.
  • A form is submitted.
  • The mouse moves over an element.

JavaScript can respond to these events.

Event Listeners

The addEventListener() method is used to run code when an event happens.

Example: Button Click

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Events</title>
</head>
<body>

    <button id="button">Click Me</button>
    <p id="message"></p>

    <script>
        let button = document.getElementById("button");
        let message = document.getElementById("message");

        button.addEventListener("click", function() {
            message.textContent = "You clicked the button!";
        });
    </script>

</body>
</html>

Output: Clicking the button changes the paragraph text.

The important part is:

button.addEventListener("click", function() {
    message.textContent = "You clicked the button!";
});

JavaScript waits for the click event and then runs the function.

Handling Forms

JavaScript can read information entered into a form and respond when the form is submitted.

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Form</title>
</head>
<body>

    <h1>Simple Form</h1>

    <form id="userForm">
        <input type="text" id="name" placeholder="Enter your name">
        <button type="submit">Submit</button>
    </form>

    <p id="message"></p>

    <script>
        let form = document.getElementById("userForm");
        let nameInput = document.getElementById("name");
        let message = document.getElementById("message");

        form.addEventListener("submit", function(event) {
            event.preventDefault();

            message.textContent = "Hello " + nameInput.value;
        });
    </script>

</body>
</html>

event.preventDefault() stops the browser from submitting and refreshing the page.

The .value property gets the text entered in the input.

Key Points

  • The DOM lets JavaScript interact with HTML.
  • getElementById() selects an element using its ID.
  • querySelector() selects an element using a CSS selector.
  • textContent changes text.
  • innerHTML can insert HTML.
  • JavaScript can change CSS using .style.
  • createElement() creates a new HTML element.
  • remove() removes an element.
  • An event is something that happens on a webpage.
  • addEventListener() lets JavaScript respond to events.
  • Forms can be handled using the submit event.

The DOM and events are what make JavaScript pages interactive.

In the next chapter, we’ll move to Modern JavaScript and look at features used in current JavaScript code.


Frequently Asked Questions (FAQs)

Q1. What is the JavaScript DOM and how does it work?

The JavaScript DOM represents an HTML page in a structure that JavaScript can access and modify. It allows JavaScript to select elements, change content and styles, create elements, and remove elements.

Q2. What is JavaScript DOM Manipulation?

JavaScript DOM Manipulation means using JavaScript to change elements and content on a webpage. Methods such as getElementById(), querySelector(), createElement(), and remove() are commonly used for this purpose.

Q3. What are JavaScript Events?

JavaScript Events are actions or occurrences on a webpage, such as a button click, key press, mouse movement, or form submission. JavaScript can detect these events and run specific code in response.

Q4. How does addEventListener work in JavaScript?

JavaScript addEventListener attaches an event listener to an HTML element. It waits for a specific event, such as click or submit, and then executes the function connected to that event.

Q5. What are DOM Events in JavaScript used for?

DOM Events in JavaScript are used to make webpages interactive. For example, a click event can change text, display information, modify styles, or perform another action when a user interacts with an element.

Q6. How can JavaScript handle form submission?

JavaScript can handle form submission using the submit event with addEventListener(). The event.preventDefault() method can stop the default page refresh, while the input’s .value property can read the entered information.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top