Use .splice () on JQuery object

We remove the child element of a specific element html

via JQuery

through:

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

      

But how can I get this to behave like a method .splice()

(like deleting a DOM

given index and offset in the tree ). For example:

  • Delete the last three children. Here I will most likely use:

    for(var x = 0; x < 3; x++) {
       $(PARENT_SELECTOR).children().last().remove()
    }
    
          

  • Remove 4-6 children. Here I will use:

    $(PARENT_SELECTOR).children().eq(3).remove()
    $(PARENT_SELECTOR).children().eq(4).remove()
    $(PARENT_SELECTOR).children().eq(5).remove()
    
          

  • Remove 5 items starting at the 5th child (this is a 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 create my own scripts for each script [that's easy]. I'm just wondering if it JQuery

already has a function like this of its own - it will shorten my scripts and not make me repeat writing similar codes.

+3


source to share


2 answers


I think $. slice is really what you are looking for. Below is an 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 it .slice()

starts at index 0, so the example above will remove the third to fifth child.

+2


source


The jQuery Slice method selects a subset of elements based on its index. This method is used to constrain the selection of items in a group by a start and end point: the start parameter is the start index (starting at 0) from which the subset is created, and the stop parameter is an optional end point. You can find a better explanation here and here



$(document).ready(function(){
    $("p").slice(1).css("background-color", "red");
    $("p").slice(2,4).remove();
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>para 0.</p>
<p>para 1.</p>
<p>para 2.</p>
<p>para 3.</p>
<p>para 4.</p>
      

Run codeHide result


+1


source







All Articles