Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get inline CSS style property from element

I have problem with getting inline css style properties.

I'd tried doing that with:

 var inline_css = $(this).attr("style");

but...

it works only when element does not have any other css properties outside inline style... like:

.our_element {something: some;}

Any ideas how to get only inline CSS properties from element which has many other CSS properties?

like image 740
luke9999 Avatar asked Oct 02 '15 09:10

luke9999


1 Answers

If you mean a style from the style attribute, you can access them directly on the element instance:

var color = this.style.color;

That will give you the color only if it's in the style attribute (not applied via stylesheet).

The names you use are camelCase if you use literal notation, e.g. this.style.fontSize, or you can also use the CSS dashed style using brackets notation, this.style["font-size"].

Just for completeness, if you want the information whether it comes from the style attribute or a stylesheet, jQuery's CSS function does just that:

var color = $(this).css("color");

From your comment:

thanks, but if I want all properties can I use this.style ??

If you want all of the inline-styles as text, either get the style attribute (as you're doing) or use this.style.cssText.

If you want all of the styles, regardless of whether they're inline or not, as an object, use getComputedStyle (or currentStyle on obsolete browsers like IE8):

var style = window.getComputedStyle ? getComputedStyle(this) : this.currentStyle;
if (style) { // This will be true on major browsers
    var color = style.color; // Or whatever
}

Examples:

var div = document.querySelector(".foo");
snippet.log("div.style.fontSize: " + div.style.fontSize);
snippet.log("div.style.color: " + div.style.color);
snippet.log("div.style.cssText: " + div.style.cssText);
snippet.log("$(div).attr('style'): " + $(div).attr('style'));
snippet.log("$(div).css('fontSize'): " + $(div).css('fontSize') + " (note that's in pixels, probably, not pt)");
snippet.log("$(div).css('color'): " + $(div).css('color'));
.foo {
  font-size: 14pt;
  color: green;
}
<div class="foo" style="font-size: 12pt">
  This has an inline <code>font-size: 12pt</code> and
  CSS (not inline) giving <code>font-size: 14pt</code> and <code>color: green</code>.
</div>
<hr>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
like image 186
T.J. Crowder Avatar answered Oct 27 '22 14:10

T.J. Crowder