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???
jQuery

Avatar of undefined
Last Comment
Michel Plungjan

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
leakim971

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
leakim971

and also $("div[data-btn='1']").css(
leakim971

find search inside the containter not at the same level
Michel Plungjan

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

Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy