0

can anyone assist in locating the anchor tag via jQuery which contains a matching data-attribute please and then applying a class to it

e.g. code

<a href="#" data-label="test1">Link 1</a>
<a href="#" data-label="test2">Link 2</a>
<a href="#" data-label="test3">Link 3</a>

So if I pass a function the value "test2" a class of highlight would be applied to that one?

Thanks

user3779703
  • 507
  • 1
  • 6
  • 20
  • Possible duplicate of [jQuery how to find an element based on a data-attribute value?](http://stackoverflow.com/questions/4191386/jquery-how-to-find-an-element-based-on-a-data-attribute-value) – Mohammad Jan 10 '17 at 14:07
  • Or [Selecting element by data attribute](http://stackoverflow.com/questions/2487747/selecting-element-by-data-attribute) – Mohammad Jan 10 '17 at 14:09

2 Answers2

1

Use attribute equals selector to get the element based on the attribute value.

$('[data-label="test2"]').addClass('active')
.active {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" data-label="test1">Link 1</a>
<a href="#" data-label="test2">Link 2</a>
<a href="#" data-label="test3">Link 3</a>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0
<a href="#" data-label="test1">Link 1</a>
<a href="#" data-label="test2">Link 2</a>
<a href="#" data-label="test3">Link 3</a>

addclass('test2');
function addclass(x){
$('[data-label="'+  x +'"]').addClass('active');
}

.active{
  color: red;
}
JabhimanyuS
  • 59
  • 1
  • 5