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? Commented Aug 20, 2015 at 17:55
  • @nrabinowitz: That's how I'd do it, yeah. Commented Aug 20, 2015 at 17:55
  • I agree with @nrabinowitz. Code snippet coming right up! Commented Aug 20, 2015 at 17:55
  • @nrabinowitz: Suggest posting that as an answer (with an example). Commented 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? Commented 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>

Sign up to request clarification or add additional context in comments.

2 Comments

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.)
@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.
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 Comments

I'm sorry, but I think you misunderstood the question.
thanks @Simon for your comment, revisiting the question, I see that I missed the point. Thanks :-)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.