Aman Singh
Aman Singh

Reputation: 753

How to get all dynamically set inline-style CSS in jQuery?

I want to get all the styles which has been set dynamically (which applies as inline-styles) on an element.

For example

<span class="text" style="color: rgb(128, 128, 255); font-size: 24px;">Name</span>

I want to get the value of style attribute in a JS variable and save it. I have tried using jQuery's .attr('style'), but it's giving undefined

Also, As suggested here How to get inline CSS style property from element to use

getComputedStyle

but to get styles I need to mention all the styles like

var el = document.querySelector("selector")
console.log(el.style.SomeStyle);

but there are various styles which a user can set dynamically. So, do I need to mention all the inline-styles individually or is there some better way to get that?

Thanks in advance for any help

Update from the void's comment:

As described here Can jQuery get all CSS styles associated with an element?

marknadal had wrote a function that retrieves both inline and external styles, but I just need the inline-styles irrespective of all css classes attached

Upvotes: 3

Views: 3015

Answers (2)

treyhakanson
treyhakanson

Reputation: 4911

You can use getAttribute:

const el = document.querySelector('my-element');
const styleStr = el.getAttribute('style');

for example, the following:

<div style="color:blue;display:flex;"></div>

would yield:

'color:blue;display:flex;'

You could then use a regex or something to parse it as needed. I'd recommend converting into an array of arrays or a similar structure rather than an object since you'll likely be unsure of what values are available (this is a simple way of doing that, and there is likely a much more efficient way to break it down. I'll leave that to you):

// gives [ ['color', 'blue'], ['display', 'flex'] ]
str.slice(0, str.length - 1).split(';').map(x => x.split(':'))

You could convert to an object and use a for in loop along with obj.hasOwnProperty(key) as well.

jQuery alternative:

const els = $('my-element');
els.each((i, el) => {
  const styleStr = els.attr('style');
  const styles = styleStr.slice(0, styleStr.length - 1).split(';').map(x => x.split(':'));
});

Upvotes: 3

FRS
FRS

Reputation: 173

You can iterate over object available under element's 'style' field as follows:

Warning That object contains also all possible styling of element (with non-numeric property keys), so looping with e.g. for (sth in styles) won't work. You need to iterate styles in array-like way like shown below.

var el = document.querySelector("selector");
var styles = el.style;

for (var i = 0, len = styles.length; i < len; ++i) {
    var name = styles[i];
    var value = styles[value];

    console.log(name); // shows style name, e.g.: color, padding, etc
    console.log(value); // shows style value, e.g.: #fff, 20px, etc
}

Upvotes: 0

Related Questions