In this section, we will explore how to select and manipulate elements in the Document Object Model (DOM) using JavaScript. This is a fundamental skill for creating dynamic and interactive web applications.

Key Concepts

  1. DOM Selection Methods

    • getElementById
    • getElementsByClassName
    • getElementsByTagName
    • querySelector
    • querySelectorAll
  2. Manipulating DOM Elements

    • Changing element content
    • Modifying element attributes
    • Changing styles
    • Adding and removing classes
  3. Practical Examples

    • Selecting elements
    • Changing text content
    • Modifying attributes
    • Changing styles dynamically
    • Adding and removing classes
  4. Exercises

    • Practice selecting and manipulating DOM elements

DOM Selection Methods

getElementById

Selects an element by its ID.

let element = document.getElementById('myElement');
console.log(element);

getElementsByClassName

Selects all elements with a specific class name. Returns an HTMLCollection.

let elements = document.getElementsByClassName('myClass');
console.log(elements);

getElementsByTagName

Selects all elements with a specific tag name. Returns an HTMLCollection.

let elements = document.getElementsByTagName('div');
console.log(elements);

querySelector

Selects the first element that matches a CSS selector.

let element = document.querySelector('.myClass');
console.log(element);

querySelectorAll

Selects all elements that match a CSS selector. Returns a NodeList.

let elements = document.querySelectorAll('.myClass');
console.log(elements);

Manipulating DOM Elements

Changing Element Content

Use the innerHTML or textContent properties to change the content of an element.

let element = document.getElementById('myElement');
element.innerHTML = 'New Content';
element.textContent = 'New Text Content';

Modifying Element Attributes

Use the setAttribute and getAttribute methods to modify attributes.

let element = document.querySelector('img');
element.setAttribute('src', 'newImage.jpg');
let src = element.getAttribute('src');
console.log(src);

Changing Styles

Use the style property to change the CSS styles of an element.

let element = document.getElementById('myElement');
element.style.color = 'red';
element.style.backgroundColor = 'yellow';

Adding and Removing Classes

Use the classList property to add or remove classes.

let element = document.querySelector('.myClass');
element.classList.add('newClass');
element.classList.remove('oldClass');

Practical Examples

Example 1: Selecting Elements

<!DOCTYPE html>
<html>
<head>
    <title>DOM Selection Example</title>
</head>
<body>
    <div id="myElement">Hello World</div>
    <div class="myClass">Class Element 1</div>
    <div class="myClass">Class Element 2</div>
    <script>
        let elementById = document.getElementById('myElement');
        console.log(elementById);

        let elementsByClassName = document.getElementsByClassName('myClass');
        console.log(elementsByClassName);

        let elementsByTagName = document.getElementsByTagName('div');
        console.log(elementsByTagName);

        let elementByQuerySelector = document.querySelector('.myClass');
        console.log(elementByQuerySelector);

        let elementsByQuerySelectorAll = document.querySelectorAll('.myClass');
        console.log(elementsByQuerySelectorAll);
    </script>
</body>
</html>

Example 2: Manipulating Elements

<!DOCTYPE html>
<html>
<head>
    <title>DOM Manipulation Example</title>
</head>
<body>
    <div id="myElement">Hello World</div>
    <img id="myImage" src="oldImage.jpg" alt="Old Image">
    <button id="changeContent">Change Content</button>
    <button id="changeImage">Change Image</button>
    <button id="changeStyle">Change Style</button>
    <button id="toggleClass">Toggle Class</button>

    <script>
        document.getElementById('changeContent').addEventListener('click', function() {
            let element = document.getElementById('myElement');
            element.innerHTML = 'New Content';
        });

        document.getElementById('changeImage').addEventListener('click', function() {
            let image = document.getElementById('myImage');
            image.setAttribute('src', 'newImage.jpg');
        });

        document.getElementById('changeStyle').addEventListener('click', function() {
            let element = document.getElementById('myElement');
            element.style.color = 'blue';
            element.style.backgroundColor = 'lightgray';
        });

        document.getElementById('toggleClass').addEventListener('click', function() {
            let element = document.getElementById('myElement');
            element.classList.toggle('highlight');
        });
    </script>
</body>
</html>

Exercises

Exercise 1: Selecting Elements

  1. Create an HTML file with multiple elements.
  2. Use different DOM selection methods to select these elements.
  3. Log the selected elements to the console.

Exercise 2: Manipulating Elements

  1. Create an HTML file with a few elements and buttons.
  2. Write JavaScript to change the content, attributes, styles, and classes of these elements when the buttons are clicked.

Solutions

Solution 1: Selecting Elements

<!DOCTYPE html>
<html>
<head>
    <title>Exercise Solution</title>
</head>
<body>
    <div id="element1">Element 1</div>
    <div class="elementClass">Element 2</div>
    <div class="elementClass">Element 3</div>
    <p>Paragraph</p>
    <script>
        let elementById = document.getElementById('element1');
        console.log(elementById);

        let elementsByClassName = document.getElementsByClassName('elementClass');
        console.log(elementsByClassName);

        let elementsByTagName = document.getElementsByTagName('div');
        console.log(elementsByTagName);

        let elementByQuerySelector = document.querySelector('.elementClass');
        console.log(elementByQuerySelector);

        let elementsByQuerySelectorAll = document.querySelectorAll('.elementClass');
        console.log(elementsByQuerySelectorAll);
    </script>
</body>
</html>

Solution 2: Manipulating Elements

<!DOCTYPE html>
<html>
<head>
    <title>Exercise Solution</title>
</head>
<body>
    <div id="element1">Element 1</div>
    <img id="image1" src="oldImage.jpg" alt="Old Image">
    <button id="changeContent">Change Content</button>
    <button id="changeImage">Change Image</button>
    <button id="changeStyle">Change Style</button>
    <button id="toggleClass">Toggle Class</button>

    <script>
        document.getElementById('changeContent').addEventListener('click', function() {
            let element = document.getElementById('element1');
            element.innerHTML = 'New Content';
        });

        document.getElementById('changeImage').addEventListener('click', function() {
            let image = document.getElementById('image1');
            image.setAttribute('src', 'newImage.jpg');
        });

        document.getElementById('changeStyle').addEventListener('click', function() {
            let element = document.getElementById('element1');
            element.style.color = 'green';
            element.style.backgroundColor = 'lightblue';
        });

        document.getElementById('toggleClass').addEventListener('click', function() {
            let element = document.getElementById('element1');
            element.classList.toggle('highlight');
        });
    </script>
</body>
</html>

Conclusion

In this section, we covered how to select and manipulate DOM elements using JavaScript. You learned about various DOM selection methods and how to change element content, attributes, styles, and classes. These skills are essential for creating dynamic and interactive web applications. In the next section, we will dive into event handling, which will allow you to make your web pages even more interactive.

JavaScript: From Beginner to Advanced

Module 1: Introduction to JavaScript

Module 2: Control Structures

Module 3: Functions

Module 4: Objects and Arrays

Module 5: Advanced Objects and Functions

Module 6: The Document Object Model (DOM)

Module 7: Browser APIs and Advanced Topics

Module 8: Testing and Debugging

Module 9: Performance and Optimization

Module 10: JavaScript Frameworks and Libraries

Module 11: Final Project

© Copyright 2024. All rights reserved