Skip to content Skip to sidebar Skip to footer

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

function onLoad() {
    var holder = document.getElementById('content');

    //simulate ajax call
    setTimeout(function() {
       // this code will be in the success handler

        var 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?
   <span id='content'></span>
 </div>

Solution 2:

You have two options, depending on which browsers you need to support:

  1. If you need to support all browsers, put your console.log code into the "success" function that's called after the ajax response. This will ensure it runs only after the div is updated by ajax.

  2. If you only need to support HTML5-compatible browsers, listen to the DOMNodeInserted event on the "name" div and instead of changing it via innerHTML, create and append the html code objects


Post a Comment for "Get DOM Element From AJAX Response With JavaScript"