function getSiblings(element, type){
var arraySib = [];
if ( type == 'prev' ){
while ( element = element.previousSibling ){
arraySib.push(element);
}
} else if ( type == 'next' ) {
while ( element = element.nextSibling ){
arraySib.push(element);
}
}
return arraySib;
}
// Example
// Html
// <ul>
// <li>Menu 1</li>
// <li>Menu 2</li>
// <li>Menu 3</li>
// <li>Menu 4</li>
// <li class="active">Menu 5</li>
// <li>Menu 6</li>
// <li>Menu 7</li>
// </ul>
var getLi = document.querySelectorAll('li');
for ( var i = 0; i < getLi.length; i++ ){
// Lets get all "li" next to "li.active"
if ( getLi[i].classList.contains('active') ){
var arrayLi = getSiblings(getLi[i], 'next');
}
}
console.log(arrayLi);
Latest version: - Add example; - Fixed 'previousSiblings' into 'previousSibling'; - Fixed 'nextSiblings' into 'nextSibling';
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.