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
- First, create a basic HTML structure and add some images.
- Then use document.images to access all <img> elements in the document.
- Then add an event listener of a button and handle the click event and with the help of the event we can change the different properties of the image.
- Within the event listener defines a loop and iterates over the image by the index where we can update the "alt", "width", and "height" attributes of each image element.
Example: The example works with document.images in JavaScript.
HTML
<!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:
Recommended Articles