Well, I have n elements with the class "class_one" and certain other elements with the class "class_two".
These elements are nested and in some cases there are other elements in that nest, what I need is to select the next element with a specific class.
let class_one = document.querySelectorAll('.class_one');
class_one.forEach(element => {
element.addEventListener('click',()=>{
console.log("From this element, the next one containing the class class_two");
})
});
<div >
click 1
</div>
<div >elemento 1</div>
<div >
click 2
</div>
<div ></div>
<div >elemento 2</div>
<div >
click 3
</div>
<div ></div>
<div >elemento 3</div>
<div >
click 4
</div>
<div >click 5</div>
<div >elemento 4</div>
<div >
click 6
</div>
<div ></div>
Personally, I would like an answer without using Jquery, but all are welcome.
CodePudding user response:
To select the next element with the class class_two
after a class_one
element using vanilla JavaScript, you can use the nextElementSibling
property of the element
object, which returns the next element sibling of the current element. For example:
let class_one = document.querySelectorAll('.class_one');
class_one.forEach(element => {
element.addEventListener('click',()=>{
let nextElement = element.nextElementSibling;
while (nextElement && !nextElement.classList.contains('class_two')) {
nextElement = nextElement.nextElementSibling;
}
if (nextElement) {
console.log(nextElement);
}
})
});
This code will loop through all the siblings after the class_one
element until it finds the next element with the class class_two
, and then it will log that element to the console. If it doesn't find any element with that class, it will log null
.
Alternatively, you can use the getElementsByClassName
method to get all the elements with the class class_two
, and then use the indexOf
method to find the index of the current element and the index of the next element with the class class_two
. For example:
let class_one = document.querySelectorAll('.class_one');
let class_two = document.getElementsByClassName('class_two');
class_one.forEach(element => {
element.addEventListener('click',()=>{
let index = class_two.indexOf(element);
if (index !== -1 && index 1 < class_two.length) {
console.log(class_two[index 1]);
}
})
});
This code will get all the elements with the class class_two
and then find the index of the current element in that list. If the index is not -1 (meaning that the element was found in the list), it will check if the next index is within the bounds of the list, and if it is, it will log the element at that index to the console. If the element is not found in the list or the next index is out of bounds, it will log null
.