4

I have an AJAX call which returns multiple HTML fragments that need replacing on the page:

<div data-replace="some-div">
  <p>whatever</p>
</div>

<div data-replace="some-other-div">
  <p>something else</p>
</div>

Currently I am adding all the html to a hidden div on the page and then doing:

    hiddenDiv.find('[data-replace]').each(function () {
        $('#' + $(this).data('replace')).html($(this).html());
        $(this).remove();
    });

which seems to work but seems a bit hacky.

Is there a better way (whilst still returning HTML rather than JSON as this is out of my control)?

3
  • 2
    Im not sure how else you would propose to do this other than storing the fragment in a JS variable. Can you not just populate the divs that need updating directly? Commented May 27, 2013 at 12:47
  • when you say populate directly, how would I do this given the format of the response? As far as I understand, I would need to parse the response to work out that (in the example) #some-div and #some-other-div need updating. Commented May 27, 2013 at 13:07
  • Well you could, as it's HTML use plain old javascript to select the dom elements in cache and then modify the div's in the DOM innerHTML property. Alternatively as you're using jQuery, why not just use that to select the right HTML and insert into the DOM? Commented May 27, 2013 at 13:17

1 Answer 1

3

I would create a jQuery object with all DOM elements and not append them to the document as an hidden DIV element since you don't need it. Also you won't need to remove it after your update.

Something like this:

(assuming that your AJAX response is a variable called data)

var $data = $("<div>" + data + "</div>");
$data.find('[data-replace]').each(function () {
    $('#' + $(this).data('replace')).html(this.innerHTML);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Nice. Thx. That seems a lot nicer than adding to the DOM in order to manipulate. So, behind the scenes, this is just done in memory and jQuery can query the variable in the same efficient way as doing so via the DOM?
@TheFlowerGuy yes. official documentation says you can can perform any of the usual jQuery methods on this object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.