How to find an element with data attribute by selector and add an event to them in jQuery?

0
(0)

For example, we have html page which contains many divs at different knots. Some of them have an attribute data-custom.

<div data-custom="text">text</div>
<div data-custom="number">123</div>
<div data-custom="char">!@#</div>

How can these divs be identified in JQuery to add onClick event to them?

In jQuery documentation we have this example:

$("input[value='Hot Fuzz']")

But with it we can find attributes with a value in search.

If you want to find an attribute with any values, just use data attribute selector “[]” without the value part:

$("[data-custom]").on("click", function() {
    console.log(this.textContent)
});

How useful was this post?

Click on a star to rate it!