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

วิธีเปลี่ยนค่า Attribute ใน JavaScript

สามารถเปลี่ยนค่า Attribute ของ Element ได้โดยตรงผ่าน Property หรือใช้ setAttribute()

ตัวอย่างโค้ด

<!DOCTYPE html>
<html>
  <body>
    <img id="HTML5" src="https://www.tutorialspoint.com/html5/images/html5-mini-logo.jpg" width="200" height="150">
    <script>
      // วิธี 1: Property (แนะนำสำหรับ Standard Attributes)
      document.getElementById("HTML5").width = "250";
      
      // วิธี 2: setAttribute() (สำหรับ Custom/Non-standard Attributes)
      // document.getElementById("HTML5").setAttribute("width", "250");
    </script>
    <p>Image width updated</p>
  </body>
</html>

วิธีการเปรียบเทียบ

วิธีSyntaxเหมาะสำหรับคืนค่า
Propertyel.width = "250"Standard Properties (id, className, href, src, width, height, value, checked...)ไม่มี (Setter)
setAttribute()el.setAttribute('width', '250')Custom Attributes, ARIA, SVG, Boolean Attributesundefined
getAttribute()el.getAttribute('width')อ่านค่า Attribute ตรง HTML (String)String/Null

ความแตกต่าง Property vs Attribute

<input type="text" value="hello">
// Property: input.value = "world" → UI เปลี่ยน, Attribute ยังคง "hello"
// Attribute: input.getAttribute('value') → "hello" (Initial)
// input.setAttribute('value', 'world') → Attribute เปลี่ยน, Property เปลี่ยน

Boolean Attributes (disabled, checked, selected, hidden...)

// Property (Boolean) - แนะนำ
input.disabled = true;
input.checked = false;

// setAttribute - ต้องมีค่า
input.setAttribute('disabled', ''); // หรือ 'disabled'
input.removeAttribute('disabled'); // ปิด

แนวทาง: ใช้ Property สำหรับ Standard Attributes ใช้ setAttribute สำหรับ Custom/ARIA/SVG