2

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>

Ryan Leach
  • 4,262
  • 5
  • 34
  • 71
  • 1
    You mean something like [**`getComputedStyle`**](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle)? – ibrahim mahrir Jul 06 '17 at 02:50
  • This link may help https://stackoverflow.com/questions/16778814/read-css-property-from-stylesheet – Aravinder Jul 06 '17 at 02:51
  • 1
    @ibrahimmahrir No, getComputedStyle is including the style attribute. – Ryan Leach Jul 06 '17 at 02:58
  • 1
    @RyanTheLeach temporarily remove the `style` attribute / property (save the value somewhere), use `getComputedStyle` then re-apply the `style` attribute / property – Phil Jul 06 '17 at 03:12
  • I was weary about modifying the styles, in case something else changed (guess nth child stuff won't be affected, as it's a rule/selector), but it's at least a solution. – Ryan Leach Jul 06 '17 at 03:17

1 Answers1

1

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.

Bla...
  • 7,228
  • 7
  • 27
  • 46