I am a JS newbie with a complex problem. I want to find out the background color of any webpage. The problem is sometime it is defined in the body tag, sometimes in inline or external css and in a more complex example some websites don't set background color on body (in some cases they do as well) but put a DIV that covers the whole page. So my problem is I want to find out the background color of the whole view. Can someone please help me.
I already tried to search before posting this question but I only found ways to get the body color not the background of the whole view so please don't mark it duplicate.
Thanks in advance
Here's a start. This will get the background-colour
of the <body>
tag, whether it's inline
or in an external stylesheet
.
function getBackground() {
var getBody = document.getElementsByTagName("body")[0]
var prop = window.getComputedStyle(getBody).getPropertyValue("background-color");
if (prop === "transparent") {
console.log("No background colour set")
} else {
console.log(prop);
}
}
getBackground();
JSFiddle Demo
You can use the pure javascript or jquery to achieve what you want. To do what you want you can use this functions
Find by tagname:
function getBackgroundByTagName(tag){
var color = $(tag).css('background-color');
console.log(color);
}
Find by class:
function getBackgroundByClassName(classname){
var color = $('.'+classname).css('background-color');
console.log(color);
}
Find by id
function getBackgroundById(idofelement){
var color = $('.'+idofelement).css('background-color');
console.log(color);
}
All you need to do is to run any of the functions and it will show the color in console.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With