JavaScript JavaScript and the DOM Getting a Handle on the DOM A Simple Example

Routine Poutine
Routine Poutine
24,081 Points

Chain addEventListener to getElementById?

Instead of:

const myHeading = getElementById('myHeading);

myHeading.addEventListener('click', ()=> { console.log('hi'); });

Can we chain them?

const myHeading = getElementById('myHeading').addEventListener('click', ()=> { console.log('hi'); });

If not, why not?

1 Answer

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 47,480 Points

Yes you can chain. The following displays in the console:

const myHeading = document.getElementById('myHeading').addEventListener('click', ()=> {
    console.log('hi');
});

But I would think you'd want the heading constant to refer to the heading element