Is it possible to use "this" with the querySelector method.
I have multiple dynamic buttons on a page and need to get the data-set values for the clicked button.
<button class="user" id="1"
data-loc="ox1"
data-name="tom">
</button>
<button class="user" id="2"
data-loc="ox2"
data-name="tom-two">
</button>
I tried the below code but it only gives the first element on the page.
[...document.getElementsByClassName("user")].forEach(function(item){
item.addEventListener("click",myFunction )
});
function myFunction() {
const user = $el.querySelector(".user");
}
I then tried using the "this" keyword but it does not work.
var $el = $(this);
const member = $el.querySelector(".user");
4
Answers
In an event handler,
this
is already set to the element the event listener was bound to (also known asevent.currentTarget
). There is no need to callquerySelector
again.The data attributes can be accessed via the
dataset
property.Also note that it is generally recommended to use event delegation on a common ancestor instead of attaching event listeners to every individual element.
I recommend to delegate too
It may be possible, but not desirable (using
this
seldom is). To simplify things, let’s use event delegation, which is especially suitable for dynamically created elements.I hope this approach can help you.