Get Dom Element From Ajax Response With Javascript
I have an AJAX request that returns a chunk of HTML as a response that is inserted into a div. How can I use JavaScript to get an element of DOM from that AJAX response HTML? I h
Solution 1:
Demo here: http://jsfiddle.net/wxCJL/1/
In this example the setTimeout call simulates the ajax request's success function, and the variable responseData is a placeholder for the HTML returned by the server.
Script
functiononLoad() {
var holder = document.getElementById('content');
//simulate ajax callsetTimeout(function() {
// this code will be in the success handlervar responseData = "<div><strong>Here I Come</strong> to save the day!</div>";
holder.innerHTML = responseData;
}, 2500);
}
Html
<h1>Hello</h1><div>
Where is the content?
<spanid='content'></span></div>Solution 2:
You have two options, depending on which browsers you need to support:
If you need to support all browsers, put your
console.logcode into the "success" function that's called after the ajax response. This will ensure it runs only after the div is updated by ajax.If you only need to support HTML5-compatible browsers, listen to the
DOMNodeInsertedevent on the "name" div and instead of changing it viainnerHTML, create and append the html code objects
Post a Comment for "Get Dom Element From Ajax Response With Javascript"