Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding background color of page or page view using Javascript

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

like image 858
a4arpan Avatar asked Jan 11 '23 11:01

a4arpan


2 Answers

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

like image 132
Nick R Avatar answered Jan 19 '23 07:01

Nick R


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.

like image 40
Zenel Rrushi Avatar answered Jan 19 '23 07:01

Zenel Rrushi