0

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?

1
  • without changing the HTML code MEANS?? Commented Apr 20, 2017 at 4:03

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0
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
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.