Reputation: 155
I have a button that is like the following,
<button type = "submit">submit</button>
how do I get JS to read the that it has been pressed without changing the HTML code?
Also I have a button that is
<button class="add">add</button>
How do I get JS to read the click without changing the code?
Upvotes: 0
Views: 55
Reputation: 2233
var buttons=document.getElementsByTagName("button");////returns an array of all buttons
//assuming that you have only one button with type == submit otherwise loop here
if(buttons[0].getAttribute("type")=="submit")
{
buttons[0].addEventListener("click",function(){
//you code goes here
});
}
var buttons=document.getElementsByClassName("add");//returns an array of buttons with class as add
//assuming that you have only one button with class add
buttons[0].addEventListener("click",function(){
//you code goes here
});
Upvotes: 0
Reputation: 150020
You would select the element using whichever one of the several DOM element selection functions (.querySelector()
, .getElementsByTagName()
, .getElementsByClassName()
, etc.) takes your fancy, attach an event listener for the click event, and then in the listener do whatever you want.
// document.querySelector('button.add') to select by class, or...
document.querySelector('button[type="submit"]').addEventListener('click', function(e) {
alert('The button was clicked.')
})
<button type = "submit">submit</button>
Note that if you had more than one button on the page then you would need to use .querySelectorAll()
(or one of the other functions I mentioned) to return a list, then loop over the list to attach event handlers to each one. Or attach a handler to their common containing element. If you want to do something different for each then you need some way to distinguish between them, e.g., if they're in different containers or something.
Upvotes: 2