A
A
Alex_js2020-05-01 10:59:55
JavaScript
Alex_js, 2020-05-01 10:59:55

How to select all buttons on a page?

While studying JS, I came to the querySelectorAll and querySelector search methods.
On an empty html page I created 2 buttons:

<body>
    <button>Show</button>
    <button>Show1</button>
</body>

And with the help of querySelectorAll I want to find 2 buttons at once and make an event on click.

let bShow = document.querySelectorAll('button');
  bShow.onclick = function () {
    // body...
    alert('Hi');
  };

Nothing works like this. But if you use , then only the first button will work. And I want a message to appear when I click on any of the buttons. Indeed, in the future, it is not very convenient to prescribe a code for each individual button. querySelector('button')

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
Tigran Abrahamyan, 2020-05-01
@Alex_js

you have to cycle through the buttons to make it work on each

let bShow = document.querySelectorAll('button');

for (let i = 0; i < bShow.length; i++) {
  bShow[i].onclick = function() {
    alert('Hi');
  }
}

M
Maxim Kirshin, 2020-05-01
@meowto16

For example

document.querySelectorAll('button[class^="Show"]');

R
ReActor Dmitry Vershansky, 2020-05-01
@HunteR-VRX

let btn = document.getElementsByTagName('button');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question