Musa Muaz
Musa Muaz

Reputation: 714

copying the same thing on same context

i have a problem with jquery i have 2 different set of icons which of each i want to the same thing:

My primary codes are

  <ul>
      <li>
          <a href="">
              <i class="fa fa-facebook"></i>
          </a>
      </li>

       <li>
          <a href="">
              <i class="fa fa-twitter"></i>
          </a>
      </li>
   </ul>

what i want after loading on my browse

  <ul>
      <li>
          <a href="">
              <i class="fa fa-facebook"></i>
              <i class="fa fa-facebook"></i>
          </a>
      </li>

       <li>
          <a href="">
              <i class="fa fa-twitter"></i>
              <i class="fa fa-twitter"></i>
          </a>
      </li>
   </ul>

i have tried to use

var socials = $("ul a");
socials.each(function ( index,elem ){
    var jumpIcons = $( this ).find("i");
    socials.append(jumpIcons);
});

but the result is browser is hangged :'(

Upvotes: 3

Views: 47

Answers (3)

Sougata Bose
Sougata Bose

Reputation: 31749

Just clone that i for each a with all the events of it(if needed) and append it to a. Try with -

var socials = $("li a");
socials.each(function ( index, elem ){
    var jumpIcons = $( this ).find("i").clone(true, true); //remove true, true if you dont need the events
    $(this).append(jumpIcons);
});

Upvotes: 3

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

You can make use of clone(), see below code

var socials = $("ul a");
socials.each(function ( index,elem ){
    var jumpIcons = $( this ).find("i").clone();//make clone of i
    $(this).append(jumpIcons);// use $(this) to get current element
}); 

Upvotes: 4

Arun P Johny
Arun P Johny

Reputation: 388316

You need to clone and add the element to the current a

var socials = $("ul a");
socials.each(function (index, elem) {
    var jumpIcons = $(this).find("i");
    //first you need to clone the current element else, you are just repositioning the current `i` elemnet
    //then you need to append it to the current a element, not to all `a` element in the socials - this will cause a lot of iteration if there a lot of `ul a` elements in the page resulting in unresponisve page
    $(this).append(jumpIcons.clone());
});

Demo: Fiddle


A simplified version

var socials = $("ul a");
socials.append(function (index, elem) {
    return $(this).find("i").clone();
});

Demo: Fiddle

Upvotes: 4

Related Questions