Error writing js to html page Uncaught TypeError: Cannot set property 'innerHTML' of null

Keywords: IE

An error occurred while getting the label and modifying the value of the label through * * * getElementById() * * * in js:
Uncaught TypeError: Cannot set property 'innerHTML' of null
Because the tag is obtained according to the id, just change the class to id

Of course, it can also be modified directly according to the method of * * * getElementsByClassName() * * *,

Because the getElementsByClassName() method returns a collection of all elements in the document with the specified class name as the NodeList object.

The NodeList object represents a sequential list of nodes. NodeList object we can access the nodes in the list through the node index number in the node list (the index number starts from 0).

<!DOCTYPE html>
<html lang="en">

<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>Document</title>
    <script>
        window.onload = function(){
            var oDiv = document.getElementById('box1');
            oDiv.innerHTML = '<a href="http://Www.bing. Com "> Bing < / a > ';
        }
    </script>
</head>

<body>
    <!-- <div class="box1">This is a div</div> -->
    <div id="box1">This is a div</div>
</body>

</html>
<!DOCTYPE html>
<html lang="en">

<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>Document</title>
    <script>
        window.onload = function () {
            var oDiv = document.getElementsByClassName('box1');
            for (i = 0; i < oDiv.length; i++) {
                oDiv[i].innerHTML = '<a href="http://Www.bing. Com "> Bing < / a > ';
            }
        }
    </script>
</head>

<body>
    <div class="box1">I'm the first div</div>
    <div class="box1">I'm the second div</div>
</body>

</html>

Posted by troinfo on Wed, 20 Nov 2019 12:55:32 -0800