简体   繁体   中英

Jquery/Javascript cannot set property innerHTML with include a page html

I include a page html in other page. In the included page I have a element with an Id. I try change the element from the other page but I have a error: Uncaught TypeError: Cannot set property 'innerHTML' of null

Part.html

<h1 id="Title">Hello</h1>

Index.html

<html>
<head>
    <title></title>
    <script src="jquery.min.js"></script>
</head>
<body>
    <div id="PartDiv"></div>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#PartDiv').load('/Part.html');
        });
    </script>

    <script type="text/javascript">
        function funct1() {
            document.getElementById("Title").innerHTML = "Bye";
        }
        funct1();
    </script>

</body>
</html>

A couple potential issues: first, your DOM element id is "title", not "Title". So your function should be:

function funct1() {
  document.getElementById("title").innerHTML = "Bye";
}

The next potential issue is that the jQuery load method is asynchronous, so you'll want to make sure you execute funct1 function in the load callback to make sure the DOM element has been loaded fist:

$('#PartDiv').load('/Part.html', funct1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM