/    Sign up×
Community /Pin to ProfileBookmark

Ok, I’ve hit a weird problem I can’t crack. Here’s some simple code to replicate:

[code]<html>
<head>
<style>
body {
background-color:#9cf !important;
}
</style>
</head>
<body style=”background-color:#fc9;”>
<script>
alert(document.body.style.backgroundColor);
</script>
</body>
</html>[/code]

Now I would expect when I echo the background color, it would echo the one that’s actually being used, but it doesn’t. It only will echo if it’s actually attached to the tag. (ie, if I change the above’s body tag to be just <body>, it gives an empty reply.)

I could, of course, parse the entire CSS to figure out just exactly which background color is applied to an element, but that seems a bit excessive and I’d rather not have to. What’s the best way to deal with this?

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@WedgeTalonauthorApr 28.2006 — I was finally able to find some info on this:

Each of these alerts would echo the correct applied style.

In IE:

alert(document.body.currentStyle.backgroundColor);

In Firefox/Mozilla:

alert(document.defaultView.getComputedStyle(document.body,null).getPropertyValue("background-color"));

Opera (at least 9) supports both methods.

The only thing you have to watch for is the format in which it is returned. IE will return it as typed. Firefox/Mozilla returns rgb(r,g,b). Opera returns #rrggbb.

Hope this might help out someone else in the future. ?
×

Success!

Help @WedgeTalon spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...