⚖️attributes vs. properties
HTML attributes vs. DOM properties
🔸 HTML attributes ┊ DOM properties┊ attr-prop sync ┊
HTML attributes
codepen ⟩ HTML attributes
⬆️ 需要: $(), $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 = 123DOM properties
DOM properties are NOT always strings. for example:
input.checked (boolean)
div.style (CSSStyleDeclaration)
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'codepen ⟩ a.href
property ⇔ attribute sync
standard attribute changes ⇒ auto-update property, and vice versa.
⭐️ with some exceptions ( 👉🏻 💈範例 )
Last updated
Was this helpful?