It is necessary with one click to make the onclick event work on several elements. The main problem is that you cannot use JS tools to simulate a click, it must be a user.

For example, it is necessary that four alerts with just one click work at once.

<p onclick='alert(1)'>text</p> <p onclick='alert(2)'>text</p> <p onclick='alert(3)'>text</p> <p onclick='alert(4)'>text</p> 

Perhaps the elements should have one class or be superimposed on each other? How to implement this?

  • It is interesting, and in what you see a difference between clicks by users and clicks from js. - KAGG Design

3 answers 3

You can do it like this (use the event ascent):

 <p onclick='alert(1)'> text <span onclick='alert(2)'> text <span onclick='alert(3)'> text <span onclick='alert(4)'>text</span> </span> </span> </p> 

But in good sense, so do not.

    Something like this, only the stranded element will generate an alert 2 times, as the first onclick will work

     let matches = document.body.querySelectorAll('p'); for(i=0; i < matches.length; i++) { matches[i].addEventListener('click', function(el){ for(j=0;j < matches.length; j++) { matches[j].click(); } }) } 
     <p onclick='alert(1)'>text</p> <p onclick='alert(2)'>text</p> <p onclick='alert(3)'>text</p> <p onclick='alert(4)'>text</p> 

    • Will it please the author? )) Основная проблема в том, что использовать средства JS для имитации клика нельзя, это должен быть пользователь. - KAGG Design
    • yes I totally agree with you - L. Vadim

    How can you, if there is a method elem.click() . The main thing is that when clicking there are no pop-up windows ( alert() not considered). Well and at once on several elements it is also possible, just write a class of some kind. The code itself:

     var all_elems = document.getElementsByClassName("your_class"); for(var i = 0; i < all_elems.length; i++){ all_elems[0].click(); } 
    • The main problem is that JS cannot be used to simulate a click, it must be a user - Grundy