Uncaught Typeerror: Cannot set Property 'src' of null

Asked

Viewed 1,144 times

0

I’m trying to load the images when I call a function but I get this mistake all the time.

HTML:

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Verificador de Idade</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <h1>Verificador de Idade</h1>
    </header>
    <section>
        <div>
            <p>Ano de Nasciment:
                <input type="number" name="txtano" id="txtano" min = "0">
            </p>
            <p>Sexo:
                <input type="radio" name="radsex" id="masc" checked>
                <label for="masc">Masculino</label>
                <input type="radio" name="radsex" id="fem">
                <label for="fem">Feminino</label>
            </p>
            <p>
                <input type="button" value="Verificar" onclick = "verificar()">
            </p>
        </div>
        <div id = "res">
            <img id = 'foto'>
            <p>Preencha os dados acima para ver o resultado!</p>
        </div>
    </section>
    <footer>
        <p>&copy; rodape</p>
    </footer>
    <script src="script.js"></script>
</body>
</html>

JS:

function verificar() {
    var data = new Date()
    var idade = Number(window.document.body.querySelector('input#txtano').value)
    var img = window.document.querySelector('img#foto')

    if(idade == 0 || idade > data.getFullYear()){
        window.alert('ERRO ao inserir ano de nascimento')
        res.innerHTML = "Insira novamente seu ano de nascimento."
    }else{
        var fsex = window.document.getElementsByName('radsex')
        idade = data.getFullYear() - idade;
        var genero = ''

        if(fsex[0].checked) {
            genero = 'homem'
            img.src = 'fotohomem.png'
        } else if(fsex[1]){
            genero = 'mulher'
            img.src = 'fotomulher.png'
        }
        res.innerHTML = `Detectamos um(a) ${genero} de idade ${idade}`
    }   
}
  • Put the whole code, for example, where fsex comes from, need to supplement your question to perform tests and get the same error as you to be able to help you.

  • Follow the @Eliseub tip. and don’t forget to insert the full error as well.

1 answer

0


In your HTML, you have the following excerpt:

<div id = "res">
    <img id = 'foto'>
    <p>Preencha os dados acima para ver o resultado!</p>
</div>

Notice that your image is inside the div with the id ""res, when in your JS, you do res.innerHTML = "...", you are replacing everything that exists inside your div with this string, including your image.

The second time your code runs, your query window.document.querySelector('img#foto') will not find any image and will return you null, so when you try to change the property src an error occurs because null has no properties.

I believe whatever you want is this:

<div>
    <img id = 'foto'>
    <p id = "res">Preencha os dados acima para ver o resultado!</p>
</div>

This way when you overwrite the internal HTML of "res", its element img will not be lost.

Browser other questions tagged

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