Searene Searene - 28 days ago 6
TypeScript Question

How to get the next sibling in addEventListener using typescript

I'm trying to get the next sibling of the element which is clicked, and I'm using typescript. Here is my code.

let jobRowList = document.getElementsByClassName('job-item');
for(let i = 0; i < jobRowList.length; i++) {
// add event listener for each element with class name job-item
let jobRow = jobRowList.item(i);
jobRow.addEventListener('click', (ev) => {
console.log(this.nextSibling); // error

However, since
is an
instead of
, it doesn't have a property called
, so typescript throws an error here.

TS2339: Property 'nextSibling' does not exist on type 'JobListTable'.

Is there any way to get the nextSibling of the clicked element using typescript?

Answer Source

this in the arrow function doesn't refer to the clicked element. You could potentially remove the arrow function and use a normal function instead - however with the arrow, you are probably looking for


jobRow.addEventListener('click', (ev) => {