Link to home
Start Free TrialLog in
Avatar of tonelm54
tonelm54

asked on

Select element based on data attribute

Is it possible to select an element based on a value set on its data attribute?

For example, I thought I could use:-
$("div").find("[data-btn='1']").css({'background-color':'#232323'});

Open in new window

So, if I had multiple elements such as:-
<div data-btn="1">1</div>
<div data-btn="2">2</div>
<div data-btn="3">3</div>
<div data-btn="4">4</div>
<div data-btn="5">5</div>

Open in new window

It would set the first element to have the background colour.

The idea eventually is be a bit more dynamic with the data value, so something like:-
$("div").find("[data-btn='" + $(this).val() . "']").css({'background-color':'#232323'});

Open in new window

But, Im just seeing if this is possible first.

eg https://jsfiddle.net/8yansth1/

Any ideas???
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
and also $("div[data-btn='1']").css(
find search inside the containter not at the same level
Alternative for you to consider

https://jsfiddle.net/mplungjan/e7ofusrw/

$(function() {
  $("button").on("click", function() {
    $('div[data-btn]').removeClass('active')
    $(`div[data-btn="${this.textContent}"]`).addClass('active')
  });
});

Open in new window


using

[data-btn="1"].active { background-color: #232323; }
[data-btn="2"].active { background-color: #ff2323; }
[data-btn="3"].active { background-color: #ffcc23; }
[data-btn="4"].active { background-color: #ffccdd; }
[data-btn="5"].active { background-color: #ffaaff; }

Open in new window