What is the perfect way to find all nextSiblings and previousSiblings in javascript. I tried few ways but not getting accurate solution. if any element is selected, I need to get length of all next siblings excluding white-space, any spaces or line-breaks
Also I don't want to use jquery for this, i specifically looking something from java script
Please advice
I'll assume that this takes place inside an event handler where
this
is a reference to the targeted element whose siblings you want to affect.If not, adjustments will be needed.
This is an update to @subhaze's answer.
This code uses the
matches
DOM method which is supported in modern browsers:Demo
Use these functions as follows:
Here is a very short and simple way to do it with ES6:
This will return all children of the parent node that are not the element.
This is a bit more winded of a solution but allows you to create a filter on how you get siblings.
There are three functions to get only previous, only next, or all. This could be improved but decent starting point if you need more control on what types of siblings you want to collect. Thought it might be worth adding.
Working Example
get all next siblings
get all previous siblings
get all siblings
example filter to apply to above functions
HTML and testing output
HTML
JavaScript
This answer was previously published here in response to a similar question .
There are a few ways to do it.
Either one of the following should do the trick.
FYI: The jQuery code-base is a great resource for observing Grade A Javascript.
Here is an excellant tool that reveals the jQuery code-base in a very streamlined way. http://james.padolsey.com/jquery/
Just my two cents here, I made a couple of functions to get all the previos and the next siblings of any element.
You just have to call this functions with a node that you can get by getElementById.