I’ve got 2 same divs and function like below. My question is, why this work only with first dedicate__wrapper ?
When I click on the second one, nothing happened, no errors in console.
$(document).ready(function() {
$(".dedicate__wrapper").on('click', function() {
var el2 = document.querySelector(".dedicate__wrapper");
var el3 = document.querySelector(".config_submit");
if (el2.classList.contains('step1')) {
el3.classList.remove('disable');
} else {
el3.classList.add('disable');
}
});
});
<div class="dedicate__wrapper"></div>
<div class="dedicate__wrapper"></div>
I tried to do add another click event, but nothing helps me. Do You have any ideas ?
2
Answers
This specifically refers to the first matching element in the DOM:
In this case, if the element you’re looking for is the one you clicked then within the jQuery click handler that’s simply
this
. For example:Or, to make further use of jQuery:
If you have additional elements to identify relative to the clicked element, then starting from
$(this)
you can traverse the DOM to find that specific element relative to the clicked element.document.querySelector
returns single element, so your conditions are applied to the first found DOM element.You will always get first matching
el2
andel3
For half code you are using plain js and for another half you are using jQuery
I would rewrite with something like this
pseudo fiddle here: https://jsfiddle.net/nitinjs/528x0syo/17/