Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use .splice() on JQuery object

We remove child of a certain html element through JQuery via:

$(PARENT_SELECTOR).children(CHILD_SELECTOR).remove()

But how can I make this behave like .splice() method (e.g. removing on the DOM tree the given index and offset). For instance:

  1. Remove the last three children. Here I'll most probably use:

    for(var x = 0; x < 3; x++) {
       $(PARENT_SELECTOR).children().last().remove()
    }
    
  2. Remove 4th to 6th children. Here I'll use:

    $(PARENT_SELECTOR).children().eq(3).remove()
    $(PARENT_SELECTOR).children().eq(4).remove()
    $(PARENT_SELECTOR).children().eq(5).remove()
    
  3. Remove 5 elements starting from the 5th child ( this is the real scenario where I want to have a .splice()-like function for JQuery ):

    var starting = 5,
        index = 5
    
    // I haven't tested this yet.
    for(var x = index + starting; x > index; x--) {
        $(PARENT_SELECTOR).children().eq(x - 1).remove()
    }
    

And the list goes on... I can make my own case-to-case scripts for each scenarios [, that's easy]. I'm just wondering if JQuery has already it's own feature like this-- it will make my scripting shorter and will not make me to repeat writing similar codes.

like image 221
Gideon Avatar asked Aug 06 '15 03:08

Gideon


People also ask

What is the use of splice () method?

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

How do you splice an array of objects?

splice() JS Array Method. The splice() method is a built-in method for JavaScript Array objects. It lets you change the content of your array by removing or replacing existing elements with new ones. This method modifies the original array and returns the removed elements as a new array.

Why is splice not working on array?

It's not working because you are removing items from the array while looping through the keys. When you remove an item, it will rearrange the other items depending on how the array is implemented internally, and you end up with a loop that doesn't iterate over the keys that you expect.

What is the use of Slice in jQuery?

The slice() is an inbuilt method in jQuery which is used to select a subset of elements based on its index. The subset is a set that may be a part of a large set. para1: It specifies that where to start the selection of the elements. para2: It is optional and it specifies where to stop the selection of the elements.


1 Answers

I think $.slice is really what you are looking for. Below is the example:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

$( "li" ).slice( 2, 4 ).remove();

Just keep in mind that .slice() starts with index 0, so example above will remove the third to fifth child.

like image 106
Bla... Avatar answered Oct 16 '22 16:10

Bla...