Take an element attribute

Asked

Viewed 785 times

2

How do I select the background color of the div element?

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>

1 answer

4

When you use el.style.backgroundColor; you’re looking for inline Styles, i.e., styles directly defined in the element. For example:

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

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

You must use window.getComputedStyle(el).backgroundColor. And by the way, if you just pass the this you already have the element you want, you don’t need the document.getElementById.

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>

  • I looked for examples on the subject, but it was not clear, now I understood. Thank you!

  • 1

    @Robisonalaxis great that I could help! If you want you can mark the answer as accepted.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.