SoulieBaby
SoulieBaby

Reputation: 5471

jquery find h2 tags and append into div

I'm trying to write a bit of jquery which finds all h2 tags inside a div (.content), then appends each one into another div (.intro).

So far I have this:

var h2 = $(".content").find("h2");
$(h2).each(function() {
  $(this).append(".intro");
});

But it's not working.. if someone could help me out, that'd be great :)

Upvotes: 0

Views: 11812

Answers (3)

user113716
user113716

Reputation: 322562

Try this:

var h2 = $('h2', '.content');
$('.intro').append(h2);

No need to use each(). jQuery has something called "implicit iteration" where you can act on the entire set at once. So you can grab them all, and append them all at the same time.

Or did you want to append a copy of them?

If so, try:

var h2 = $('h2', '.content');
$('.intro').append(h2.clone());

EDIT:

Or use a single line version:

$('.intro').append($('h2', '.content').clone());​

(of course, remove .clone() if you don't need to copy them.)

Upvotes: 5

wsanville
wsanville

Reputation: 37516

I think you're looking for the appendTo method.

var h2 = $(".content").find("h2");
$(h2).each(function() {
    $(this).clone().appendTo($(".intro"));
});

Edit: Just noticed that appendTo was moving the h2 tags, so incase that is not desired, added the call to clone().

Upvotes: 2

Damon Skelhorn
Damon Skelhorn

Reputation: 1511

Could use children(), something like...

$('.content').children('h2').each(function() {
    $(this).appendTo($('.intro'));
});

Upvotes: 3

Related Questions