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

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

หากต้องการดึงจำนวนรูปภาพในเอกสาร ให้ใช้คุณสมบัติ images ใน JavaScript

ตัวอย่าง

ลองรันโค้ดด้านล่างเพื่อดึงจำนวนรูปภาพ:

<!DOCTYPE html>
<html>
  <body>
    <img src="https://www.tutorialspoint.com/html5/images/html5-mini-logo.jpg">
    <img src="https://www.tutorialspoint.com/hive/images/hive-mini-logo.jpg">
    <img src="https://www.tutorialspoint.com/sas/images/sas-mini-logo.jpg">
    <img 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);
    </script>
  </body>
</html>

document.images คืนค่า HTMLCollection ของแท็ก <img> ทั้งหมดในเอกสาร ใช้ .length เพื่อนับจำนวน สามารถเข้าถึงแต่ละรูปได้ด้วยดัชนี document.images[0], document.images[1] ฯลฯ หรือผ่าน name/id