Pour sélectionner les éléments frères siblings
d’un élément, on définit une méthode sur l’objet Element
qui va chercher tous ces éléments frères suivants, c’est-à-dire tous les éléments suivants de même niveau que l’élément courant. Une méthode cherchant tous les éléments frères en pur javascript peut également être développée. De même, on peut imaginer une méthode retournant les éléments frères précédents.
Principe, code
On va chercher l’élément frère suivant avec la propriété nextSibling
et tant qu’il existe un élément suivant, on continue, en stockant l’élément courant dans un tableau.
1 2 3 4 5 6 7 8 9 |
Element.prototype.getNextSiblings = function() { let siblings = []; let sibling = this.nextSibling; while (sibling && sibling.nodeType == 1) { siblings.push(sibling); sibling = sibling.nextSibling; } return siblings; }; |
Méthode pour obtenir tous les frères siblings
Pour cela, on sélectionne l’élément parent parentNode
puis le premier enfant avec la propriété firstChild
:
1 2 3 4 5 6 7 8 9 10 11 |
Element.prototype.getSiblings = function() { let siblings = []; let sibling = this.parentNode.firstChild; while (sibling && sibling.nodeType === 1) { if (sibling == this ) continue; siblings.push(sibling); sibling = sibling.nextSibling } return siblings; }; |
Méthode pour obtenir tous les frères siblings précédents
1 2 3 4 5 6 7 8 9 10 |
Element.prototype.getPrevSiblings = function() { let siblings = []; let sibling = this.parentNode.firstChild; while (sibling && sibling.nodeType === 1 && sibling !== this) { siblings.push(sibling); sibling = sibling.nextSibling } return siblings; }; |
Et hop, trois méthodes simples pour sélectionner les éléments frères d’un élément.