kb_
kb_

Reputation: 1335

Remove single child at index

There's examples to detach all children after a given index (like this one), but nothing to just remove one.

Things I have tried (which are obviously incorrect):

this.element.find('.nav-tabs').children().splice(index, 1).remove();
this.element.find('.nav-tabs').children().slice(index).detach();

and some other variations on that. I need something like the second option that preserves the children after that index as well. What am I missing? Can I splice it and reassign the children somehow?

Upvotes: 4

Views: 10790

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337656

You can use eq() to target an element in a collection by its index. Try this:

this.element.find('.nav-tabs').children().eq(index).remove();

Here's a working demo:

$('.nav-tabs').children().eq(2).remove(); // remove third item, index 2
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<ul class="nav-tabs">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>

The reason splice() and slice() don't work for you is because they return an array of DOM Element objects, not a jQuery object.

Upvotes: 10

user4164128
user4164128

Reputation:

If the community is also interested in a pure javascript solution. Here's mine.

The parameter 'el' represents any DOM element. 'index' refers to the 'el' childnode you desire to remove.

function removeSpecificNode(el, index) {
    var children = el.children;
    if(children.length > 0) {
        el.removeChild(children[index]);
    }
}

And with offset. Removes all childnodes to the given offset.

function removeNodesToOffset(el, offset) {
    var children = el.children;
    for(var i=children.length-1;i>=0+offset;i--)
        el.removeChild(children[i]);
}

Upvotes: 3

Related Questions