Copying the same thing in the same context

I have a problem with jquery. I have 2 different sets of icons, which from each I want the same:

My primary codes

  <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 into my view

  <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 tried to use

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

      

but as a result the browser hangs: '(

+3


source to share


3 answers


You need to clone and add the item 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




Simplified version

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

      

Demo: Fiddle

+4


source


You can use 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
}); 

      

+4


source


Just clone

that i

for everyone a

with all of events

it (if necessary) and append

up 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);
});

      

+3


source







All Articles