Forum Moderators: open

Message Too Old, No Replies

Getting attributes of an element

Scripts from my notes, thought it might help others

         

csdude55

5:28 pm on Jul 31, 2023 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm going through all of my old notes and came across these little treasures that I thought might help others. I didn't write either of them myself, just scripts I had found somewhere along the way.

// this will show EVERY attribute for an element where ele is the ID of the element
var css_obj = getComputedStyle(document.getElementById(ele));

for (i = 0; i < css_obj.length; i++)
console.log(css_obj[i] + ': ' + css_obj.getPropertyValue(css_obj[i]));


// this shows all of the styles that are set for the element
const node = document.getElementById(ele);
const attributeNodeArray = [...node.attributes];
const attrs = attributeNodeArray.reduce((attrs, attribute) => {
attrs[attribute.name] = attribute.value;
return attrs;
}, {});

console.log(attrs);