Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีดึง ID ของรูปภาพแรกในเอกสารด้วย JavaScript

หากต้องการดึง ID ของรูปภาพแรก ให้ใช้คุณสมบัติ images ใน JavaScript

ตัวอย่าง

ลองรันโค้ดด้านล่างเพื่อดึง ID ของรูปภาพแรกในเอกสาร:

<!DOCTYPE html>
<html>
  <body>
    <img id="image1" src="https://www.tutorialspoint.com/html5/images/html5-mini-logo.jpg">
    <img id="image2" src="https://www.tutorialspoint.com/hive/images/hive-mini-logo.jpg">
    <img id="image3" src="https://www.tutorialspoint.com/sas/images/sas-mini-logo.jpg">
    <img id="image4" src="https://www.tutorialspoint.com/maven/images/maven-mini-logo.jpg">
    <script>
      var val = document.images.length;
      document.write("<br>Number of images in the document: "+val);
      document.write("<br>The id of the first image: "+document.images[0].id);
    </script>
  </body>
</html>

document.images[0] เข้าถึงรูปภาพแรกในเอกสาร แล้วอ่านคุณสมบัติ .id ได้ค่า "image1" สามารถเข้าถึงคุณสมบัติอื่นได้ เช่น .src, .alt, .width, .height, .name