Using JS and AJAX, I am loading a template file on my Index.html page. Once the template is loaded, I then want to apply changes to the DOM.
- The template is successfully loading on the index.html page.
- The JS is FAILING to update the DOM elements.
What am I doing wrong?
I have 2 html pages.
- index.html
- page-banner-area.html
index.html
<div id="page-banner-area"></div>
<script>
$(function(){
$("#page-banner-area").load("assets/static_html/page-banner-area.html");
$("#title").text('Join a Community Group in your area.');
$("#keypoint-1").text('We are against mandatory vaccines & passports.');
$("#keypoint-2").text('We do not stand for corruption & censorship.');
$("#keypoint-3").text('We believe in freedom!');
});
</script>
page-banner-area.html
<div class="p-2 flex-grow-1">
<h3><span id="title"></span></h3>
<span id="keypoint-1"></span><br />
<span id="keypoint-2"></span><br />
<span id="keypoint-3"></span>
</div>
CodePudding user response:
The problem is that the load()
method is asynchronous, you need to do your changes within a callback method in order for them to be properly applied. See the JQuery docs for more information https://api.jquery.com/load/
As for a solution, you should be doing this instead:
$(function(){
$("#page-banner-area").load("assets/static_html/page-banner-area.html", function() {
$("#title").text('Join a Community Group in your area.');
$("#keypoint-1").text('We are against mandatory vaccines & passports.');
$("#keypoint-2").text('We do not stand for corruption & censorship.');
$("#keypoint-3").text('We believe in freedom!');
});
});
CodePudding user response:
I thinks this can solve your problem!
<div id="page-banner-area"></div>
<script>
$(() => {
$("#page-banner-area")
.load("assets/static_html/page-banner-area.html", () => {
$("#title").text('Join a Community Group in your area.');
$("#keypoint-1").text('We are against mandatory vaccines & passports.');
$("#keypoint-2").text('We do not stand for corruption & censorship.');
$("#keypoint-3").text('We believe in freedom!');
});
});
</script>