Brad Leach
Brad Leach

Reputation: 16997

jQuery: Chopping up ajax'ed HTML an then injecting it into the DOM

I am loading some html from a remote source via the jQuery $.ajax() method.

Before I insert the html into the DOM, I want to chop it up into three pieces and insert each individual part into a particular area of my DOM.

For example, lets assume I load the following content via the $.ajax() function:

<div class='first'>First</div>
<div class='second'>Second</div>
<div class='third'>Third</div>

And want to insert it into this page connected to the DOM:

<div class='firstHome'>Some content I want replaced.</div>
<div class='secondHome'>More content to replace.</div>
<div class='thirdHome'>Final location for content.</div>

which would result in:

<div class='firstHome'><div class='first'>First</div></div>
<div class='secondHome'><div class='second'>Second</div></div>
<div class='thirdHome'><div class='third'>Third</div></div>

How can I achieve that with jQuery?

Upvotes: 1

Views: 72

Answers (2)

Kevin B
Kevin B

Reputation: 95017

Pick the content out of the returned html and append it.

var $frag = $(returnedhtml);

$(".firstHome").html($frag.find(".first").addBack(".first"));
$(".secondHome").html($frag.find(".second").addBack(".second"));
$(".thirdHome").html($frag.find(".third").addBack(".third"));

The above code will only work in jQuery 1.9+, for previous versions, use this:

var $frag = $(returnedhtml);

$(".firstHome").html($frag.find(".first").andSelf().filter(".first"));
$(".secondHome").html($frag.find(".second").andSelf().filter(".second"));
$(".thirdHome").html($frag.find(".third").andSelf().filter(".third"));

Upvotes: 2

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262979

A simple each() loop should get the job done:

$(yourContent).each(function() {
    $("." + this.className + "Home").empty().append(this);
});

Upvotes: 1

Related Questions