133 votes

Impossible de définir la propriété 'innerHTML' de null.

Pourquoi est-ce que je reçois une erreur ou Uncaught TypeError : Impossible de définir la propriété 'innerHTML' de null ? Je pensais avoir compris innerHTML et l'avoir fait fonctionner auparavant.

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>

<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = 'hi';
    };
</script>

</head>

<body>
<div id="hello"></div>
</body>
</html>

5voto

Voici mon extrait, essayez-le. J'espère qu'il vous sera utile.

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
</head>

<body>

<div id="hello"></div>

<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = 'hi';
    };
</script>
</body>
</html>

5voto

user6175882 Points 51
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example</title>

</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = '<p>hi</p>';
    };
</script>  
</body>
</html>

4voto

Eddy Points 41

Vous pourriez essayer d'utiliser la méthode setTimeout pour vous assurer que votre html se charge en premier.

3voto

Pines Tran Points 61

La cause fondamentale est : Le HTML d'une page doit être chargé avant le code javascript. . Résolu de 2 façons :

1) Permettre le chargement du HTML avant le code js.

<script type ="text/javascript">
    window.onload = function what(){
        document.getElementById('hello').innerHTML = 'hi';
    }
</script>

//or set time out like this:
<script type ="text/javascript">
    setTimeout(function(){
       what();
       function what(){
          document.getElementById('hello').innerHTML = 'hi';
       };
    }, 50);
    //NOTE: 50 is milisecond.
</script>

2) Déplacer le code js sous le code HTML

<div id="hello"></div>
<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = 'hi';
    };
</script>

1voto

user2114253 Points 119
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = 'hi';
    };
</script>
</body>
</html>

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X