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)?
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With