Image exchange using js

Asked

Viewed 31 times

-1

I’m trying to change the image according to the schedules but it’s not working someone can help me? the images are respective to their schedules, follow the code right down

<body onload="carregar()">

<header>
    <h1>Hora do dia</h1>
</header>

<section>
    <div id="msg">
        aqui vai aparecer a msg
    </div>
    <div id="imagem">
        <img src="fotomanha.png" alt="Foto de manhã">
    </div>
</section>

<footer>
    <p>&copy; On</p>
</footer>

<script>
    function carregar() {
var msg = document.getElementById('msg')
var img = document.getElementById('imagem')
var data = new Date()
var hora = data.getHours()
msg.innerHTML = `Agora são ${hora} horas.`

if (hora >= 0 && hora < 12) {
    //Bom dia
    img.src = 'fotomanha.png'
} else if (hora >= 12 && hora < 18) {
    //Boa tarde
    img.src = 'fototarde.png'
} else {
    //Boa noite
    img.src = 'fotonoite.png'
}

}

</script>

1 answer

0


in the variable img you’re picking up the div and not the element <img /> to catch the element img only do so var img = document.querySelector('#imagem > img')

Browser other questions tagged

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