HTML attributes vs. DOM properties
Last updated 2 years ago
Was this helpful?
🔸 ┊ ┊ ┊
For element nodes, most standard HTML attributes automatically become properties of DOM objects. 📗 JS.info ⟩
<body id="page"> => body.id="page"
JS.info ⟩ ⟩ ⟩
MSN ⟩
Element ⟩
:
- elem.attr()
attribute name is case-insensitive.
attribute values are always strings.
element.attributes collection is iterable and has all the attributes as objects with name and value properties.
codepen ⟩
⬆️ 需要: $(), $all(), elem.attr()
📁 HTML
<div id="div" about="Elephant">DIV</div>
📁 JS
const {log} = console; const div = $('div'); // ⭐️ attribute name is case-insensitive log(div.attr('About')); // Elephant log(div.attr('ABOUT')); // Elephant log(div.attr('AboUt')); // Elephant // ⭐️ set new attribute test="123" div.attr('Test', 123); // <div id='div' about='Elephant' test='123'>DIV</div> // ⭐️ Note: div.attributes is NOT an array. for (let attr of div.attributes) { log(`${attr.name} = ${attr.value}`); } // about = Elephant // test = 123
DOM properties are NOT always strings. for example:
input.checked (boolean)
div.style ()
a.href is always a full URL. ( 👉🏻 See: 💈範例 )
/* -------- helper -------- */ // show element's attribute & property function showAttrProp(elem, attr, prop=attr){ log(`${elem.nodeName.toLowerCase()}.${prop} = ${elem[prop]}`); log(`${attr}='${elem.attr(attr)}'`); } /* -------- ⭐️ `a.href` is always a full URL -------- */ const a = $('a'); showAttrProp(a, 'href'); // a.href = 'https://...#hello' // ⭐️ full URL // href='#hello'
standard attribute changes ⇒ auto-update property, and vice versa.
⭐️ with some exceptions ( 👉🏻 💈範例 )
<input>
const {log} = console; let input = $('input'); /* -------- ⭐️ input.value => value="..." NOT synced -------- */ // input.value => user's current input // input.defaultValue => value="..." (attribute) // (介面) ╱‾‾‾‾‾‾‾‾‾‾‾ ✅ ‾‾‾‾‾‾‾‾‾‾‾‾‾⤵︎ // input.attr('value', 'hi') input.value = 'hi' // ↖___________ ❌ _____________╱ (裡面) // input.attr('value') =✅=> input.value input.attr('value', 'hi'); show(); // input.value = 'hi' ✅ synced // <input value='hi'> // input.value =❌=> attribute input.value = 'what?'; show(); // input.value = 'what?' // <input value='hi'> ❌ NOT synced // show input's attribute & property function show(){ log(`input.value = '${input.value}'`); log(input.outerHTML); }
JS.info ⟩
- 竟然沒有 "⤴" 的左右對稱字元❗️