I have an HTML table and have set up event listeners for each row:
var greyHeadings = document.querySelectorAll(".grey");
console.log(greyHeadings);
greyHeadings.forEach(function(greyHeading){
greyHeading.addEventListener('click', function(e){
displayDescription(e, greyHeading);
});
});
The function which is called ( displayDescription
) is the following one:
function displayDescription(e, greyHeading){
var desc = e.target.parentNode.nextSibling.firstChild;
console.log(desc);
}
It does get me the correct target, but it seems that nextSibiling.firstChild
does not work. I need to get to the next row (so, the sibling), and find the first td (so, the first Child), so i can add a active
class to it, -in case you're wondering.
I have also created a jsfiddle: https://jsfiddle.net/7vpzLfke/
I am a beginner, so an explanation which is a little bit more detailed would be greatly appreciated!
First, select the parent of the element whose siblings that you want to find. Second, select the first child element of that parent element. Third, add the first element to an array of siblings. Fourth, select the next sibling of the first element.
nextSibling returns the next node (an element node, a text node or a comment node). Whitespace between elements are also text nodes. nextElementSibling returns the next element (not text and comment nodes).
jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.
You will have to use nextElementSibling
instead of nextSibling
, since nextElementSibling
always returns an HTML Element. More on that here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With