⚖️attributes vs. properties
HTML attributes vs. DOM properties
Last updated
Was this helpful?
HTML attributes vs. DOM properties
Last updated
Was this helpful?
Was this helpful?
🔸 HTML attributes ┊ DOM properties┊ attr-prop sync ┊
DOM properties are NOT always strings. for example:
input.checked
standard attribute changes ⇒ auto-update property, and vice versa.
⭐️ with some exceptions ( 👉🏻 💈範例 )
element.attributes collection is iterable and has all the attributes as objects with name and value properties.
div.style (CSSStyleDeclaration)
a.href is always a full URL. ( 👉🏻 See: 💈範例 )
<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);
}
<div id="div" about="Elephant">DIV</div>
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
/* -------- 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'