4

In Javascript, can I retrieve the CSS values of an element without taking account of its inline style?

example:

body { font-size: 15px; }

<body style="font-size: 20px;">

Is there a way I can retrieve "15px" and not "20px"?

8
  • 2
    Ditch the style attribute, get computed style, then add the style attribute back? Aug 20, 2015 at 17:55
  • @nrabinowitz: That's how I'd do it, yeah. Aug 20, 2015 at 17:55
  • I agree with @nrabinowitz. Code snippet coming right up! Aug 20, 2015 at 17:55
  • @nrabinowitz: Suggest posting that as an answer (with an example). Aug 20, 2015 at 17:56
  • But if there is CSS transition on the property, wouldn't I risk seeing a glitch by adding and removing the inline-style? Aug 20, 2015 at 17:56

2 Answers 2

5

Yes, of course! Just get rid of the style attribute, use getComputedStyle(), and add the style attribute back:

//Get the body's style attribute:
var bodyStyle = document.body.getAttribute("style");
//Now, get rid of it:
document.body.removeAttribute("style");
//Now use getComputedStyle() to compute the font size of the body and output it to the screen:
document.write( getComputedStyle(document.body).fontSize );
//Now add the style attribute back:
document.body.setAttribute("style", bodyStyle);
body { font-size: 15px; }
<body style="font-size: 20px;">
</body>

2
  • I'd've given nrabinowitz a bit more time to post his comment as an answer, or at least make the answer a CW. (Frustrating when people post answers as comments, but I always CW when I decide to repost it as an answer.) Aug 20, 2015 at 18:00
  • @T.J.Crowder Oh...I was already working on the code snippet before that comment was posted. It's just that I saw a new comment and responded so people would know I was making a snippet. Aug 20, 2015 at 18:03
0
   var a = document.getElementsByTagName('body');
   console.log (a[0].attributes.style);  // returns the current inline style
   a[0].setAttribute('style','font-size : 15px'); // change it as required
2
  • I'm sorry, but I think you misunderstood the question. Aug 20, 2015 at 18:56
  • thanks @Simon for your comment, revisiting the question, I see that I missed the point. Thanks :-)
    – maaeab
    Aug 20, 2015 at 22:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.