Home > Software design >  How to keep only the first element from a class when cloning with jquery
How to keep only the first element from a class when cloning with jquery

Time:12-02

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.

CodePudding user response:

You can keep first div by adding :first.

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

CodePudding user response:

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>

or you can select the first one by class selection as @Manashree Shah mentioned like this:

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

The code 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>
  • Related