Search code examples
javascriptjqueryjquery-selectorstraversalsiblings

How do I delete the next two siblings and ONLY the next two siblings in this pop-up using jQuery?


So I have a popup. You click on an "+Add Text" link and it adds a text box to the page, along with another "+Add Text link" and an "x" in a span on the right corner of each textbox. When I click an "x" within this popup, I'd like for it to delete the two siblings that immediately follow it. The HTML generated on the page looks something like this...

 <div class="popup">
   <div class="delete-text-box-x">X</div>  
   <textarea class="textbox"></textarea>
   <span class="add-textbox">+Add text</span>
   <div class="delete-text-box-x">X</div>
   <textarea class="textbox"></textarea>
   <span class="add-textbox">+Add text</span>
   <div class="delete-text-box-x">X</div>
   <textarea class="textbox"></textarea>
   <span class="add-textbox">+Add text</span>
</div>

When I click the divs with the class "delete-text-box-x">, I'd like for the following two siblings to be deleted. That is, the following corresponding textarea and "+Add Text" span.

I almost have it. Here is my jQuery

$('.delete-text-box-x').click(_.bind(function(e){
  $('.delete-text-box-x').nextUntil('.add-textbox').remove();
}, this)); 
}

It's obvious why this doesn't work. The nextUntil method does indeed select and remove the textboxes following the 'X' divs. But the selector selects EVERY 'X' on the page, and therefore deletes EVERY textbox on the page. It also doesn't delete the '+Add Textbox' spans...

So how do I get more specific than the current selector I'm using? So it selects ONLY the specific 'X' I click, rather than every 'X' on the page.


Solution

  • Firstly, you need to base the selector on the element that raised the event using the this keyword. From there you can use nextUntil(), but you should use the selector of the next X so that all the required elements are found. Finally you need to use add() to include the clicked X itself. Try this:

    $('.delete-text-box-x').click(function (e) {
        $(this).nextUntil('.delete-text-box-x').add(this).remove();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="popup">
        <div class="delete-text-box-x">X</div>
        <textarea class="textbox"></textarea> 
        <span class="add-textbox">+Add text</span>
    
        <div class="delete-text-box-x">X</div>
        <textarea class="textbox"></textarea> 
        <span class="add-textbox">+Add text</span>
    
        <div class="delete-text-box-x">X</div>
        <textarea class="textbox"></textarea> 
        <span class="add-textbox">+Add text</span>
    </div>

    I also note you're using some odd syntax around the anonymous function in the click handler which I presume this is due to another library. If not you should remove it.