Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector targeting element with id AND class does not work

I have the following event-handling function:

jQuery(document).on('click', '#button .submitb', function(e){alert();});

jQuery IS included in the html document. But, if I click on a <div id="button" class="submitb">Go!</div> nothing happens. I don't even get an error in the chrome-console.

like image 627
Fly Avatar asked Dec 15 '25 02:12

Fly


2 Answers

If you want to target the same element, then you cannot have a space between selectors, that would mean .submitb descendent of #button.

And since the element has ID you just actually need the id selector:

jQuery(document).on('click', '#button', function(e){alert();});

EDIT:

You cannot have multiple buttons with same ID!! then you should use just the class. Or give them different ID-ending like _0, _1 and target with [id^=button]

like image 176
Sergio Avatar answered Dec 16 '25 15:12

Sergio


.submitb is not a descendant of #button to target it with jquery just use the id `#button'

like this

jQuery(document).on('click', '#button', function(e){alert();});

If you want to target a div id with that class aswell you can you just move the space.

like this

jQuery(document).on('click', '#button.submitb', function(e){alert();});

like image 38
rorypicko Avatar answered Dec 16 '25 16:12

rorypicko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!