How to return the id of the first image in a document with JavaScript?

To return the id of the first image in a document, use the document.images property in JavaScript. This property returns a collection of all image elements in the document.

Syntax

document.images[0].id

How It Works

The document.images collection contains all <img> elements in the document, indexed starting from 0. To get the first image's id, access document.images[0].id.

Example

Here's a complete example showing how to get the id of the first image:

<!DOCTYPE html>
<html>
   <body>
      <img id="image1" src="/html5/images/html5-mini-logo.jpg" alt="HTML5">
      <img id="image2" src="/hive/images/hive-mini-logo.jpg" alt="Hive">
      <img id="image3" src="/sas/images/sas-mini-logo.jpg" alt="SAS">
      <img id="image4" src="/maven/images/maven-mini-logo.jpg" alt="Maven">
      
      <script>
         var totalImages = document.images.length;
         var firstImageId = document.images[0].id;
         
         document.write("<br>Number of images in the document: " + totalImages);
         document.write("<br>The id of the first image: " + firstImageId);
      </script>
   </body>
</html>
Number of images in the document: 4
The id of the first image: image1

Alternative Approach Using Modern JavaScript

You can also use querySelector to get the first image element:

<!DOCTYPE html>
<html>
   <body>
      <img id="firstImg" src="/html5/images/html5-mini-logo.jpg" alt="HTML5">
      <img id="secondImg" src="/maven/images/maven-mini-logo.jpg" alt="Maven">
      
      <script>
         // Using querySelector to get first image
         var firstImage = document.querySelector('img');
         console.log('First image ID:', firstImage.id);
         
         // Using document.images (traditional approach)
         console.log('First image ID (traditional):', document.images[0].id);
      </script>
   </body>
</html>
First image ID: firstImg
First image ID (traditional): firstImg

Error Handling

Always check if images exist before accessing their properties:

<!DOCTYPE html>
<html>
   <body>
      <script>
         if (document.images.length > 0) {
            console.log('First image ID:', document.images[0].id);
         } else {
            console.log('No images found in the document');
         }
      </script>
   </body>
</html>
No images found in the document

Conclusion

Use document.images[0].id to get the first image's id. Always check if images exist before accessing their properties to avoid errors.

Updated on: 2026-03-15T23:18:59+05:30

584 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements