How to find the target button in jQuery?

In a document click event, how to return if the target is a button element

$(document).click(function(e){ if(e.target.nodeName.toLowerCase() != 'button') 

Is the above code correct?

+6
source share
5 answers

You can only do

 $(document).click(function(e) { if ( $( e.currentTarget ).is( ":button" ) ) { // Do things } }); 

Why use :button instead of button ?

This way you can determine if there is a <input type="button"> OR a <button> , as well as other input types that appear as buttons.
If you are not sure about using this selector, select : jQuery docs button selector .

+17
source

Faster:

 $(this).is('button'); 
+3
source

You can use .is () to test this element for a selector.

You can also use : button to check, if you want only the element button, then you can use the is('button') element selector

 $(document).click(function(e) { if ($( e.target ).is(":button")) { //check } }); 
+3
source
 $(document).click(function(e){ if($(this).is('button')){ //your codes.. } }); 
+2
source

Pure JS FTW!

 e.target.nodeName === 'BUTTON' 

or if you have an array of dom elements

 if(['BUTTON', 'INPUT'].indexOf(e.target.nodeName) !== -1){ // clicked on button/input } 

It's not a mistake. Uppercase letters for HTML.

In XHTML (or any other XML format), the value of text_field will read "DIV". However, in HTML, text_field will read "DIV" because the nodeName and tagName in uppercase HTML elements in the DOM are marked as HTML documents.

https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeName

+1
source

Source: https://habr.com/ru/post/948466/


All Articles