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

วิธีดึงข้อความที่แสดงบนปุ่มด้วย JavaScript

หากต้องการดึงข้อความที่แสดงบนปุ่มใน JavaScript ให้ใช้คุณสมบัติ innerHTML

ตัวอย่าง

ลองรันโค้ดด้านล่างเพื่อเรียนรู้วิธีแสดงข้อความที่มองเห็น:

<!DOCTYPE html>
<html>
  <body>
    <form id="myForm">
      <button id="btn" type="button">My Button</button>
    </form>
    <script>
      var str = document.getElementById("btn").innerHTML;
      document.write("Button text: "+str);
    </script>
  </body>
</html>

ผลลัพธ์: "Button text: My Button" สำหรับ <button> ใช้ innerHTML หรือ textContent เพื่อดึงข้อความภายใน (รองรับ HTML tags ภายใน) สำหรับ <input type="button"> ใช้ .value แทน เพราะไม่มีเนื้อหาภายใน