John John - 1 month ago 8
HTML Question

How do I change innerHTML of loaded page with JQuery

I want my jquery to change text inside blocks with class "ToChange". It works fine inside current html file, but it does not with external html file (that I insert with "load" method). Here is my code:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<title>Home page</title>
<script src="jquery-3.1.1.js"></script>
<script>
$(function(){
$('.insert_external').load("external.html");
});
</script>
<script>
$(function(){
length = document.getElementsByClassName("ToChange").length;
for (i = 0; i < length; i++) {
document.getElementsByClassName("ToChange")[i].innerHTML = "New Text";
}
});
</script>
</head>

<body>
<div class="insert_external"></div>

<div class="ToChange">
This changes fine
</div>
<div class="ToChange">
This changes fine too
</div>
</body>
</html>


external.html

<div class="ToChange">
This text does not change :(
</div>


As result I see 3 strings:

This text does not change :(

New Text

New Text


And I want all of them to be "New Text". Is it possible to do so using only html and js with jquery?

Answer

You have to change the html inside load() callback so the new data is here, else it will change in the old DOM since the JS works asynchronously.

You've to wait for the .load() to finish the request :

$('.insert_external').load("external.html", function() {
    length = document.getElementsByClassName("ToChange").length;
    for (i = 0; i < length; i++) {
        document.getElementsByClassName("ToChange")[i].innerHTML = "New Text";
    }
});

NOTE : Since you're using jQuery it'll be better to use .each() function instead :

$('.insert_external').load("external.html", function() {
    $(".ToChange").each(function(){
        $(this).text("New Text");
    })
})

Hope this helps.