Style background image with JS not working

GtOkAi picture GtOkAi · Oct 1, 2014 · Viewed 11.3k times · Source

Ok, maybe its a stupid question with a little bug, but I'm trying fix this and I can not:

    <style>
 .pagar a {   
 width:  200px;
 height: 85px;
 display: block; 
 background-image: url('imagens/pagar.jpg'); 
 background-repeat: no-repeat;

     } 
.pagar a:hover { 
 background-image: url('imagens/pagar-hover.jpg');
 background-repeat: no-repeat; } 
</style>

    <script>
    function clickado() {
    document.getElementsByClassName('pagar')[0].style.backgroundImage = 'url("imagens/pagar-clickado.jpg")';
    }
    </script>

HTML:

<div class="pagar" id="pagar" ><a href="#" onclick="clickado()"></a></div>

The problem:

The .style.backgroundImage just does not change to "imagens/pagar-clickado.jpg", the the path is correct, I do not get error in console and ('pagar')[0] is also correct too.

Answer

A1rPun picture A1rPun · Oct 1, 2014

I think you wanted to target the a element inside the div.pagar. You can do something like this:

HTML

<div class="pagar" ><a href="#" id="pagar" onclick="clickado()"></a></div>

Javascript

function clickado() {
    document.getElementById('pagar').style.backgroundImage = 'url("imagens/pagar-clickado.jpg")';
}