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:-
The idea eventually is be a bit more dynamic with the data value, so something like:-
eg https://jsfiddle.net/8yansth1/
Any ideas???
For example, I thought I could use:-
$("div").find("[data-btn='1']").css({'background-color':'#232323'});
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>
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'});
But, Im just seeing if this is possible first.eg https://jsfiddle.net/8yansth1/
Any ideas???
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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/
using
https://jsfiddle.net/mplungjan/e7ofusrw/
$(function() {
$("button").on("click", function() {
$('div[data-btn]').removeClass('active')
$(`div[data-btn="${this.textContent}"]`).addClass('active')
});
});
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; }