Andrew
Andrew

Reputation: 3673

How can I get a list of all inline-styles?

There's an easy way to find all current attributes on an HTMLElement using el.attributes, but I can't find an equivalent for inline-styles. I've tried seeing if anyone else ran into this problem but there seems to be no relative results.

Doing something like this I was able to find all possible styles, but it also included all the functions and irrelevant data.

for( var style in el.style ){ 
    console.log(el.style[style]); 
}

This is a very wasteful computation for a loop that can be as large as 300+ iterations with a potential of 100% of the inline-styles not actually set to anything. Is there a better way?

Upvotes: 2

Views: 3228

Answers (3)

Unmitigated
Unmitigated

Reputation: 89527

If you only need an array of set inline CSS properties, you can simply convert the style of the element to an array with spread syntax or Array.from.

function getInlineStyleProperties(elem){
  return [...elem.style];
}
console.log(getInlineStyleProperties(document.querySelector('div')));
<div style="height: 20px; color: red;"></div>

To get an object mapping the set properties to their values, you can convert the style of the element to an array with spread syntax to get all the set properties, map over it to create an array of key-value pairs, and use Object.fromEntries to convert it to an object.

function getInlineStyles(elem){
  return Object.fromEntries([...elem.style].map(x => [x, elem.style[x]]));
}
console.log(getInlineStyles(document.querySelector('div')));
<div style="height: 20px; color: red;"></div>

Upvotes: 3

user670839
user670839

Reputation:

The modern way of doing it is this:

function getInlineStyle (element) {
  return Array.from(element.style).reduce((style, name) => {
    style[name] = element.style[name]
    return style
  }, {})
}

const div = document.getElementById('foo')
console.log(getInlineStyle(div))
<div id="foo" style="width: 100px; margin-top: 10px;"></div>

Upvotes: 0

Andrew
Andrew

Reputation: 3673

Note: I did have the answer before posting this question, but I was going to ask it anyways and think it would be helpful to other people

The style object returned by nodes has a length property which is the number of currently defined inline-styles. You can use this property to loop over the style object as an array-like structure and each index returns the name that is defined.

Example:

for (var i = 0, l = el.style.length; i < l; i++){
    console.log(el.style[i]); // an active inline-style
}

Upvotes: 1

Related Questions