Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plain Javascript: event.target : Get the next Sibling, & the first Child [duplicate]

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!

like image 837
user74843 Avatar asked Jun 21 '17 12:06

user74843


People also ask

How do you target siblings in JavaScript?

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.

What is next element sibling in JavaScript?

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).

How can I get next sibling in jQuery?

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.


1 Answers

You will have to use nextElementSibling instead of nextSibling, since nextElementSibling always returns an HTML Element. More on that here

like image 156
Komninos Avatar answered Oct 11 '22 18:10

Komninos