How to find a "div" with attribute "data-status" and add an event to them?

Viewed 137

I have a website which contains many divs. Some of them have an attribute data-status.

Example:

<div data-status="read">+-*</div>
<div data-status="unread">123</div>
<div data-status="sticked">xyz</div>

I want to add an onClick event to them. How can I identify these divs in Jquery?

These divs are not siblings! They are at different knots.

I found this example

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

on api.jquery.com, but with it I can find attributes with a value equal to my search only. But in my case, I want to find an attribute with any values. Is it possible?

1 Answers

Simple as the attribute selector you already used "[]" - just, without the value part:

$("[data-status]").on("click", function() {
  console.log(this.textContent)
});
<div data-status="read">+-*</div>
<div data-status="unread">123</div>
<div data-status="sticked">xyz</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The same selector can be used in CSS too - if you'll ever need it:

[data-status] {
  color: gold;
}
<div data-status="read">+-*</div>
<div data-status="unread">123</div>
<div data-status="sticked">xyz</div>

Related