Ryan Leach
Ryan Leach

Reputation: 4470

Get an elements style inherited from classes *not* style attribute

How can I get the style of a div, that is being applied from stylesheets/style tags and ignore the element style programmatically?

e.g.

var alice = 'alice ' + $('.alice').css('color');
var boblice = 'alice ' + $('.bob').css('color');
var bob = 'bob ' + $('.bob').css('color');

$('#result').text(
alice + '\n' + bob
);

$('#expected').text(
boblice + '\n' + bob
);

var elem1 = document.getElementById("alice");
alicestyle = window.getComputedStyle(elem1, null);

console.log(alicestyle);
.alice {
  color:green;
}

.bob {
  color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='alice' class="alice" style="color:red">
test
</div>

<div id = 'bob' class="bob">
test
</div>

result:
<div id="result">

</div>

expected:
<div id="expected">

</div>

getComputedStyle:
<div id="computed">

</div>


Upvotes: 2

Views: 304

Answers (1)

Bla...
Bla...

Reputation: 7288

Well, I don't think you can get the style directly from the stylesheets. But I think you can use below code for a workaround:

if( typeof( $('#alice').attr('style') ) != 'undefined' ) { 
   $('#alice').removeAttr('style'); 
   var aliceSheets = $('.alice').css('color');
   console.log(aliceSheets);
} 

If you want to get the style only without changing the style of the element then you can add the style attribute back after reading the color.

Upvotes: 1

Related Questions