Reputation: 691
I'd like to load html content from a template file (b.xhtml), insert it to the calling file (a.xhtml) and then update the inserted node (e.g. add/delete attributes etc.).
The insertion part works fine, but the DOM doesn't seem to get updated.
Here's the test case.
a.xhtml (the calling html file)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#placeholder").load("b.xhtml #id2");
// why doesn't this work?
var myTemp = document.querySelector("#id2");
if (myTemp) {
alert(myTemp.innerHTML);
} else {
alert("#id2 is undefined");
};
});
});
</script>
</head>
<body>
<h1>jQuery load test</h1>
<div><button>Load template</button></div>
<div id="placeholder"></div>
</body>
</html>
b.xhtml (the template html file)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div id="templates">
<p id="id1">This is template one</p>
<p id="id2">This is template two</p>
</div>
</body>
</html>
Upvotes: 4
Views: 8908
Reputation: 1289
Try to do it like this:
<script>
$(document).ready(function(){
$("button").click(function(){
$("#placeholder").load("b.xhtml #id2",function()
{
var myTemp = document.querySelector("#id2");
if (myTemp) {
alert(myTemp.innerHTML);
} else {
alert("#id2 is undefined");
};
});
});
});
</script>
Upvotes: 1
Reputation: 1616
The .load() method is asynchronous, so your script is executing that line but not waiting for it to finish before it goes on to the next line. You can do a couple things. First, use a callback function:
$("#placeholder").load("b.xhtml #id2", function(){
var myTemp = document.querySelector("#id2");
if (myTemp) {
alert(myTemp.innerHTML);
} else {
alert("#id2 is undefined");
};
});
Or, use .done():
$("#placeholder").load("b.xhtml #id2").done(function(){
var myTemp = document.querySelector("#id2");
if (myTemp) {
alert(myTemp.innerHTML);
} else {
alert("#id2 is undefined");
};
});
Upvotes: 9