Loading...

Go Back

Next page
Go Back Course Outline

JavaScript Full Course


Working with the DOM (Document Object Model)

Working with the DOM (Document Object Model) in JavaScript

The DOM (Document Object Model) is a programming interface for web documents. It represents the structure of an HTML document as a tree of nodes, where each node is an object representing a part of the document (such as an element, attribute, or text). The DOM allows programming languages like JavaScript to interact with the content, structure, and styles of web pages dynamically.

DOM Tree Structure:

  • Document: The root node representing the entire document.
  • Element nodes: Represent HTML tags (e.g., <div>, <p>, etc.).
  • Text nodes: The textual content inside HTML elements.
  • Attribute nodes: Attributes of elements like class, id, etc.

1. Selecting Elements

In JavaScript, you can select and interact with elements on the page using various methods:

1.1. getElementById()

This method returns the element with the specified id.

                        <!DOCTYPE html>
                        <html lang="en">
                        <head>
                            <meta charset="UTF-8">
                            <title>getElementById Example</title>
                        </head>
                        <body>
                            <h1 id="heading">Hello World!</h1>
                            <script>
                                const element = document.getElementById('heading');
                                console.log(element.innerText);  // Output: Hello World!
                            </script>
                        </body>
                        </html>
                                

1.2. getElementsByClassName()

This method returns a live HTMLCollection of elements with the specified class name.

                        <!DOCTYPE html>
                        <html lang="en">
                        <head>
                            <meta charset="UTF-8">
                            <title>getElementsByClassName Example</title>
                        </head>
                        <body>
                            <div class="box">Box 1</div>
                            <div class="box">Box 2</div>
                            <script>
                                const boxes = document.getElementsByClassName('box');
                                console.log(boxes.length);  // Output: 2
                                console.log(boxes[0].innerText);  // Output: Box 1
                            </script>
                        </body>
                        </html>
                                

1.3. getElementsByTagName()

This method returns a live HTMLCollection of elements with the specified tag name.

                        <!DOCTYPE html>
                        <html lang="en">
                        <head>
                            <meta charset="UTF-8">
                            <title>getElementsByTagName Example</title>
                        </head>
                        <body>
                            <p>Paragraph 1</p>
                            <p>Paragraph 2</p>
                            <script>
                                const paragraphs = document.getElementsByTagName('p');
                                console.log(paragraphs.length);  // Output: 2
                                console.log(paragraphs[1].innerText);  // Output: Paragraph 2
                            </script>
                        </body>
                        </html>
                                

1.4. querySelector()

This method returns the first element that matches the specified CSS selector.

                        <!DOCTYPE html>
                        <html lang="en">
                        <head>
                            <meta charset="UTF-8">
                            <title>querySelector Example</title>
                        </head>
                        <body>
                            <div class="box">Box 1</div>
                            <div class="box">Box 2</div>
                            <script>
                                const firstBox = document.querySelector('.box');
                                console.log(firstBox.innerText);  // Output: Box 1
                            </script>
                        </body>
                        </html>
                                

1.5. querySelectorAll()

This method returns all elements that match the specified CSS selector as a NodeList.

                        <!DOCTYPE html>
                        <html lang="en">
                        <head>
                            <meta charset="UTF-8">
                            <title>querySelectorAll Example</title>
                        </head>
                        <body>
                            <div class="box">Box 1</div>
                            <div class="box">Box 2</div>
                            <script>
                                const allBoxes = document.querySelectorAll('.box');
                                allBoxes.forEach(box => console.log(box.innerText));  // Output: Box 1, Box 2
                            </script>
                        </body>
                        </html>
                                


2. Manipulating Elements

2.1. Changing Content

Use .innerText or .innerHTML to change the text or HTML content of an element.

                        <!DOCTYPE html>
                        <html lang="en">
                        <head>
                            <meta charset="UTF-8">
                            <title>Change Content</title>
                        </head>
                        <body>
                            <p id="para">Original Text</p>
                            <script>
                                const para = document.getElementById('para');
                                para.innerText = 'Updated Text!';
                            </script>
                        </body>
                        </html>
                                

2.2. Changing Attributes

Use .setAttribute() to change an element’s attribute.

                        <!DOCTYPE html>
                        <html lang="en">
                        <head>
                            <meta charset="UTF-8">
                            <title>Change Attribute</title>
                        </head>
                        <body>
                            <img id="image" src="old-image.jpg" alt="Old Image">
                            <script>
                                const image = document.getElementById('image');
                                image.setAttribute('src', 'new-image.jpg');
                                image.setAttribute('alt', 'New Image');
                            </script>
                        </body>
                        </html>
                                

2.3. Changing Styles

Use .style to manipulate the styles of an element.

                        <!DOCTYPE html>
                        <html lang="en">
                        <head>
                            <meta charset="UTF-8">
                            <title>Change Styles</title>
                        </head>
                        <body>
                            <div id="box" style="width:100px; height:100px; background-color:red;"></div>
                            <script>
                                const box = document.getElementById('box');
                                box.style.backgroundColor = 'blue';
                                box.style.width = '200px';
                            </script>
                        </body>
                        </html>
                                

3. Creating and Adding Elements

You can create new HTML elements dynamically and add them to the DOM:

                        <!DOCTYPE html>
                        <html lang="en">
                        <head>
                            <meta charset="UTF-8">
                            <title>Create and Add Elements</title>
                        </head>
                        <body>
                            <div id="container"></div>
                            <script>
                                const container = document.getElementById('container');
                                const newDiv = document.createElement('div');
                                newDiv.innerText = 'Newly created div!';
                                container.appendChild(newDiv);
                            </script>
                        </body>
                        </html>
                                

4. Removing Elements

To remove an element from the DOM, use .remove() or .parentNode.removeChild().

                        <!DOCTYPE html>
                        <html lang="en">
                        <head>
                            <meta charset="UTF-8">
                            <title>Remove Element</title>
                        </head>
                        <body>
                            <div id="box">This will be removed</div>
                            <script>
                                const box = document.getElementById('box');
                                box.remove();  // Removes the box from the DOM
                            </script>
                        </body>
                        </html>
                                

5. Event Handling

Event listeners allow you to respond to user interactions like clicks, keypresses, etc.

5.1. Adding Event Listeners

Use .addEventListener() to listen for events on elements.

                        <!DOCTYPE html>
                        <html lang="en">
                        <head>
                            <meta charset="UTF-8">
                            <title>Event Listener Example</title>
                        </head>
                        <body>
                            <button id="myButton">Click Me</button>
                            <script>
                                const button = document.getElementById('myButton');
                                button.addEventListener('click', function() {
                                    alert('Button was clicked!');
                                });
                            </script>
                        </body>
                        </html>
                                

6. DOM Traversal

Navigating the DOM tree allows you to move between nodes (parent, child, sibling).

                        <!DOCTYPE html>
                        <html lang="en">
                        <head>
                            <meta charset="UTF-8">
                            <title>DOM Traversal Example</title>
                        </head>
                        <body>
                            <div id="parent">
                                <p id="child">This is a child element</p>
                            </div>
                            <script>
                                const child = document.getElementById('child');
                                const parent = child.parentNode;
                                console.log(parent);  // Output: 
...
</script> </body> </html>
Go Back

Next page