[Dart] Visit All Sibling Elements or Nodes


DOM manipulation - traverse all sibling elements or nodes via Dart.

Visit All Sibling Elements

Use nextElementSibling and previousElementSibling:

var sibling = elm.nextElementSibling;
while (sibling != null) {
  // do something with the sibling element

  sibling = sibling.nextElementSibling;
}
sibling = elm.previousElementSibling;
while (sibling != null) {
  // do something with the sibling element

  sibling = sibling.previousElementSibling;
}

Visit All Sibling Nodes

Use nextSibling and previousSibling:

var sibling = node.nextSibling;
while (sibling != null) {
  // do something with the sibling node

  sibling = sibling.nextSibling;
}
sibling = node.previousSibling;
while (sibling != null) {
  // do something with the sibling node

  sibling = sibling.previousSibling;
}

Difference Between Element and Node

In short, nodes include pure texts, comments, or elements. And elements are something like div, p, or any other HTML tags. Elements are one kind of nodes. For more details, see [1] and [2]

Example

See my another post [Dart] Tab Panel [3]. We traverse the sibling elements of tab pane to remove the .active class of other tab pane.


Tested on:

  • DartPad
  • Chromium Version 58.0.3029.110 Built on Ubuntu , running on Ubuntu 17.04 (64-bit)

References:

[1]javascript - Whats the difference between nextElementSibling vs nextSibling - Stack Overflow
[2]HTML DOM nextElementSibling Property
[3][Dart] Tab Panel
[4][JavaScript] Visit All Sibling Elements or Nodes