简体   繁体   中英

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?

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
}

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM