Catch the attribute of an element

2

How do I select the color of the div element's backGround?

Note: Using javascript

var cor;
cor = document.getElementById(id).style.backgroundColor;
#bloco1 {
    width: 280px;
    height: 120px;
    border: 1px dashed black;
    position: relative;
    background-color: blue;
}
<!DOCTYPE html>
<html lang 'pt-br'>

    <head>
        <title>Pintar</title>
    </head>

    <body>
        <div id='bloco1' onclick='selecionarCor(this.id)'></div>
    </body>

</html>
    
asked by anonymous 24.11.2016 / 14:39

1 answer

4

When you use el.style.backgroundColor; you are looking for inline styles , ie styles defined directly in the element. For example like this:

<div id='bloco1' style="background-color: #00f;"></div>

In this case it will not give you anything because your CSS is not inline but rather as CSS in a separate file.

You should use window.getComputedStyle(el).backgroundColor . And by the way, if you pass only the% w / o to the function you already have the element you want, you do not need% w / o%.

function selecionarCor(el) {
    var cor = window.getComputedStyle(el).backgroundColor;
	alert(cor);
}
#bloco1 {
    width: 280px;
    height: 120px;
    border: 1px dashed black;
    position: relative;
    background-color: blue;
}
<!DOCTYPE html>
<html lang 'pt-br'>

    <head>
        <title>Pintar</title>
    </head>

    <body>
        <div id='bloco1' onclick='selecionarCor(this)'></div>
    </body>

</html>
    
24.11.2016 / 14:46