1

I was trying this:

$(document).ready(function () {
    $(".qa-a-count").appendTo(".qa-q-item-main");
});

But there are a lot of .qa-a-count and .qa-q-item-main divs. They end up being appened to each other. How can I do it so that they only append to their parent div (.qa-q-item-main div)?

gdoron
  • 147,333
  • 58
  • 291
  • 367
alexchenco
  • 53,565
  • 76
  • 241
  • 413

2 Answers2

3
$('.qa-a-count').each(function() {
   // .parent() if this is a direct child of `qa-q-item-main`
   $(this).appendTo($(this).closest('.qa-q-item-main')); 
});

This will go through each of .qa-a-count and append to its ancestor.

Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
  • What about `.parent()`? I thought of using it instead of `.closest`. I might be wrong just want to know the reason behind `.closest` – Ajinkya May 24 '12 at 08:21
  • @Ajinkya. closest will find the element if it's its "ancestor" not just "parent". – gdoron May 24 '12 at 08:22
  • @Ajinkya if `.qa-a-count` is a direct child of `.qa-q-item-main`, then yes use `parent`, since I didn't know your markup, the safest I could go is to use `closest` – Andreas Wong May 24 '12 at 08:22
  • @NiftyDude: I think OP wants to append it to ONLY parents. – Ajinkya May 24 '12 at 08:23
  • @Ajinkya. No, he want to append `$('.qa-a-count')` only to it's ancestor. – gdoron May 24 '12 at 08:24
  • @gdoron: I think I got confused by this line `How can I do it so that they only append to their parent div` – Ajinkya May 24 '12 at 08:27
1
$(".qa-a-count").each(function (){
    // append this- (the current ".qa-a-count") 
    // to it's closest ".qa-q-item-main" element.
    $(this).appendTo($(this).closest(".qa-q-item-main"));
});

Or cache $(this):

$(".qa-a-count").each(function (){
    var $this = $(this);
    $this.appendTo($this.closest(".qa-q-item-main"));
});

But it's not that big performance boost if you're iterating a huge number of elements.
What is the cost of '$(this)'?

Community
  • 1
  • 1
gdoron
  • 147,333
  • 58
  • 291
  • 367