Andrew Koper
Andrew Koper

Reputation: 7191

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 have JavaScript at the end of the returned HTML response div, but getElementById returns null, apparently because the DOM hasn't been created, and I can't use window.onload like on a normal web page. See eample below. And this has to be in JavaScript - no libraries.

<div class="page-content extractAjaxContent" id="tableContent_AJAX">
<div id="name">Biff</div>
    <html:form action="/variableCostStatusPost" method="post">
     ....some JSP to produce HTML
    </html:form>
<script>console.log("Name is " + document.getElementById('name'));</script>
</div>

Upvotes: 0

Views: 7394

Answers (2)

Don Rhummy
Don Rhummy

Reputation: 25830

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

Upvotes: 0

Jason
Jason

Reputation: 15931

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>

Upvotes: 1

Related Questions