⚖️attributes vs. properties
HTML attributes vs. DOM properties
HTML attributes
<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 = 123DOM properties
/* -------- 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'property ⇔ attribute sync
Last updated