Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clone and append multiple elements in place with jQuery?

What is a simple way to duplicate every element in a class as a sibling? For example, it should change this HTML:

<body>
    <div> 
        <h1> Foos </h1>
        <span class='duplicate-me'> foo </span>
    </div>
    <div>
        <h1> Bars </h1> 
        <span class='duplicate-me'> bar </span>
    </div>
</body>

into:

<body>
    <div> 
        <h1> Foos </h1>
        <span class='duplicate-me'> foo </span>
        <span class='duplicate-me'> foo </span>
    </div>
    <div>
        <h1> Bars </h1> 
        <span class='duplicate-me'> bar </span>
        <span class='duplicate-me'> bar </span>
    </div>
</body>

Thanks

like image 564
Zachary Nagler Avatar asked Mar 10 '23 10:03

Zachary Nagler


1 Answers

$('.duplicate-me').after(function() {
  return $(this).clone();
});

Use the after method from jQuery and call the clone method in the function you are passing to it.

References: http://api.jquery.com/after/

http://api.jquery.com/clone/

Example: https://jsfiddle.net/2y6cqLrq/

like image 52
Sean Wessell Avatar answered Mar 12 '23 23:03

Sean Wessell