简体   繁体   中英

How to keep only the first element from a class when cloning with jquery

Each of my divs have a class attributes named remove , the first class has the id: remove_item then the second remove_item_1 , the third remove_item_2 , etc.

My problem is that i only want to clone first one with the id remove_item and remove all the other one from the clone.

If i do clone.find('.remove'); i am able to gather all the elements with remove class but from there i am kinda lost on how to do that.

Could anyone help?

Thanks.

You can keep first div by adding:first.

clone.find('.remove:first');

I think I got what you mean

here's an example how to pick the first element of a cloned div:

lets say you have

<ul id="list">
        <div id="clone">
            <li class="remove remove1">Remove 1 </li>
            <li class="remove remove2">Remove 2</li>
            <li class="remove remove3">Remove 3</li>
        </div>
    </ul>

The script to clone the list and remove the first child of the clone goes like this:

<script>
        let clone = $('#clone').clone().appendTo('#list');
        clone.children().first().remove();
    </script>

This one uses jQuery, you can add this before the script if you haven't already added it:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM