Open In App

How to use document.images in JavaScript ?

In JavaScript, the document.images property returns a collection of all "<img>" elements within the current document. We can manipulate these images using various properties and methods. We will see how to work with document.images in JavaScript.

Approach

Example: The example works with document.images in JavaScript.

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>Manipulating Images with JavaScript</title>
    <style>
        body {
            height: 100vh;
            margin: 0;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .container {
            text-align: center;
        }

        h2 {
            margin-top: 0;
            color: #14e611;
            font-size: 2.3rem;
        }

        img {
            border: 2px solid black;
            margin-left: 50px;
        }

        button {
            margin-top: 20px;
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 5px;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #0056b3;
        }
    </style>
</head>

<body>

    <div class="container">
        <h2>Images Manipulation Example 
              with document.images
          </h2>

        <div class="img_container">
            <img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20240308154939/html-(1).jpg" 
                 alt="Image 1"
                 width="200" height="150">
            <img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20240308154940/js-(1).jpg" 
                 alt="Image 2"
                 width="200" height="150">
            <img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20240308154942/web-(1).jpg" 
                 alt="Image 3"
                 width="200" height="150">
            <img src="" alt="Image 4" 
                 width="200" height="150">
        </div>
        <button id="btn">Change Image Attributes</button>
    </div>

    <script>
        let btn = document.querySelector("#btn");
        btn.addEventListener("click", function () {
            let images = document.images;
            for (let i = 0; i < images.length; i++) {
                let image = images[i];
                image.alt = `Alt has Changed ${i}`;
                image.width = 300;
                image.height = 200;
            }

        });

    </script>

</body>

</html>

Output:

documentimages

Output :document.images in JavaScript

Article Tags :