Mohammed H
Mohammed H

Reputation: 7048

How to use document.getElementById with jquery next siblings selector

I want to remove some silblings. I tried as given below. But not working. why? And how to solve it?

<div>
  <div id="idx1">child1 </div>
  <div id="idx2">child2</div>
  <div id="idx3">child3</div>
  ...
  <div id="/a/b/c">This should be last child</div>
  <div id="idx4">Remove it.</div>
  <div id="idx5">Remove it.</div>
  <div id="idx6">Remove it.</div>
  ...
</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<script>

 // Since the id contains special chars,
 // javascript method has been used to get the element.
 lastChildObj = jQuery(document.getElementById('a/b/c')); 

 // I don't know how to remove the childs after lastChildObj.
 // I tried as given below.
 lastChildObj.filter('~').remove();

Upvotes: 0

Views: 2099

Answers (5)

Cerbrus
Cerbrus

Reputation: 72867

This should work for you:

var base = document.getElementById('/a/b/c');
while(base.nextSibling){ // While the element has siblings
    base.parentElement.removeChild(base.nextSibling); // remove the siblings from the parent element.
}

Working example

You can also make it slightly more efficient:

var base = document.getElementById('/a/b/c');
while(base.parentElement.removeChild(base.nextSibling))​ // Remove the nextSiblings while they exist.

Example

Upvotes: 1

Samuel Caillerie
Samuel Caillerie

Reputation: 8275

Try this :

$("#\\/a\\/b\\/c").nextAll().remove();

JsFiddle : http://jsfiddle.net/QcvWQ/

Upvotes: 0

wakooka
wakooka

Reputation: 1428

You can still use jquery for your selector but you need to escape the id like so :

$("#\\/a\\/b\\/c")

Then you just need to select any following divs like this :

$("#\\/a\\/b\\/c").nextAll().remove();

http://jsfiddle.net/8mMJq/

Further informations about special characters in selectors : http://api.jquery.com/category/selectors/

Upvotes: 1

Marcin Buciora
Marcin Buciora

Reputation: 449

First of all change id from "/a/b/c" to ie "abc" and then run following

$("#abc").nextAll().each(function () { $(this).remove());});

Upvotes: -2

Anthony Grist
Anthony Grist

Reputation: 38345

There are two key steps to this.

  1. Select the elements to remove
  2. Remove them

Step 1 can be broken down into two parts, obtaining a reference to the last element to keep, then getting a list of all of its siblings that come after it. Step 2 just uses the .remove() function.

$(document.getElementById('/a/b/c')).nextAll().remove();

Upvotes: 1

Related Questions