views:

117

answers:

3

Hi all, 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 :)

+2  A: 

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().

wsanville
+2  A: 

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.)

patrick dw
+2  A: 

Could use children(), something like...

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