Andriy Zahura
Andriy Zahura

Reputation: 45

addEventListener byt tag

I have a file structure like

<div id='root'>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</div>

Those <li><li> tags include some content, and I would like to open/close them, but using a pure javascript only. I've tried so using the document.querySelectorAll, for now the code goes something like this

let lis = document.querySelectorAll('#root > li');
function show(e) {
  alert('hey');
}
lis[1].addEventListener('click', show(), false);

But it alerts only when I refresh the page, not "listening" to the actual click, and I still don't know how to refer a precise element. Maybe there are some articles I could use?

P.S. I can't modify the HTML code, so I can't use document.getElementById, and jQuery is also not for me at the moment. Thanks a lot in advance.

Upvotes: 2

Views: 65

Answers (2)

Dupinder Singh
Dupinder Singh

Reputation: 7769

According to the https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Your code is working fine, and there is not an issue of page reload, its triggered instantly

let lis = document.querySelectorAll('#root > li');
function show(e) {
  alert('hey');
} debugger;
lis[1].addEventListener('click', show, false);
<p>
  Just for info we are applying listener to lis[1] it means list 2 because array starts with 0 😋
lis[1].addEventListener('click', show(), false);
</p>

<div id='root'>
    <li>List 1</li>
    <li>List 2</li>
    <li>List 3</li>
    <li>List 4</li>
</div>

Upvotes: 0

The Fool
The Fool

Reputation: 20467

The issue is that you invoke the show function instead of passing it to the addEventListener method.

You should pass the function so that it can be invoked later when the event occurs.

lis[1].addEventListener('click', show, false);

Upvotes: 2

Related Questions