I’m performing an ajax call to grab an HTML page from the server; ajax call looks like this:
function loadHtml() {
$.ajax({
type : 'GET',
async : false,
url : 'my.html',
contentType : 'text/html',
dataType : 'html',
success : function(data) {
loadedHtml = data; // the loadedHtml variable is global
}
});
}
Later, I’d like to display this html after modifying it somewhat.
Attempt 1
I tried this, but the resulting screen shows nothing at all (body contains no html).
var myContent = $(loadedHtml).find('#test1').text("Modified!");
$('body').html(myContent);
Attempt 2
I also tried this, but the resulting screen just shows the original content of loadedHtml.
var myContent = $(loadedHtml);
myContent.find('#test1').text("Modified!");
$('body').html(myContent);
Original Html
Here’s the original content of loadedHtml from my.html
<div id="test1" style="color: white;"> Working! </div>
What am I doing wrong?
UPDATES
- This is a simple example I’m trying to get to work before adding the complexity of what I really need to be doing. So, using a simple string replace on the
loadedHtmlvariable before inserting it into the DOM is not something that will work for me. - I’ve updated my code to show the ajax call is synchronous. the
loadedHtmlvariable does in fact contain the html from the server by the time I get to the point I’m trying to modify it.
You misuse the
findfunction:It search only descendants, In your case
#test1isn’t a child…so this:
Won’t grab the test1 element, it’s not a descendant.