14

Is there a JavaScript method similar to jQuery .next()? I want to find the next element that has the class of "error" relative to the element. I've tried using .nextSibling as a loop but couldn't figure it out. Didn't know if there was an easier way to go about it without jQuery.

For instance, if I have this code:

<div id="section">
    <div id="test">test</div>
    <span class="info">Information</span>
    <span class="error">Error!</span>
</div>

I'm trying to get the next .error class closest to #test, if I have a #section2 and a #test2 I would want to get the .error class closest to #test2 and so on.

Jonas
  • 121,568
  • 97
  • 310
  • 388
Howdy_McGee
  • 10,422
  • 29
  • 111
  • 186
  • 2
    I suspect you might misunderstand what `.next(selector)` does. It doesn't search through siblings to match the selector. It just filters, either collecting the very next sibling if it matches or nothing. – Jonathan Lonowski Dec 17 '13 at 03:16

4 Answers4

14

The nextElementSibling property returns the element immediately following the specified element, in the same tree level.

Example: Get the HTML content of the next sibling of a list item:

var x = document.getElementById("item1").nextElementSibling

The nextElementSibling property might help.

Unheilig
  • 16,196
  • 193
  • 68
  • 98
swartkatt
  • 368
  • 3
  • 10
  • The `nextElementSibling` just return `next sibling` element not `next` element. For example, if we have hierarchical elements it just returns the next element of our element in the parent block – Amir Astaneh Dec 30 '20 at 18:57
3

Best bet would be to search through the jQuery code and see what they did. http://code.jquery.com/jquery-2.0.3.js

At a glance, I do see some calls to "nextSibling" and "previousSibling."

Also see here: How to get next element using JavaScript-only?

Hope this helps!

Community
  • 1
  • 1
kmiklas
  • 13,085
  • 22
  • 67
  • 103
2

This is the pure javascript for you:

HTML

<div id="nodes">
    <div class="error">This is error Node</div>  
    <div class="nextElement">This is next Element</div>
</div>

Javscript:

var nodes = Array.prototype.slice.call( document.getElementById('nodes').children ),
    errorNode = document.getElementsByClassName('error')[0];
var indexOfError = nodes.indexOf(errorNode);
var nextElement = nodes[indexOfError + 1];
alert(nextElement.innerText);

Here is demo

Ringo
  • 3,795
  • 3
  • 22
  • 37
0

Sounds like you may be looking for document.getElementsByClassName()... if the elements with class=error are not direct siblings in the DOM, then there's not a good way to find them otherwise. It's elementary, but you can just search through the array returned by document.getElementsByClassName('error') until you find your starting element, and then you know the next item in the array will be the next element in the DOM.

See also MDN reference. Won't work in old IE, but works for all modern browsers.

Hylianpuffball
  • 1,553
  • 10
  • 13