IGGt IGGt - 2 months ago 9
jQuery Question

jQuery AddClass matching class and value

I have the following:

<span class="dateStart" val="0">2016-09-16</span> |
<span class="dateStart" val="1">2016-09-15</span> |


Using jQuery how can I add a class of
selected
to the
<span>
that has
class=dataStart
AND
val=1
.

I tried:

$('.dateStart[value="0"]').addClass('selected');
$('.dateStart[val="0"]').addClass('selected');
$('.dateStart[attr-val="0"]').addClass('selected');


But none of them work. Am I even close?

Answer

You want to add class "selected" in a span having class "dateStart" and attribute "val" having "1" so selector should be $('.dateStart[val="1"]').addClass('selected');

function getSelected(){
  $('.dateStart[val="1"]').addClass('selected');
}
.selected{
  color:red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="dateStart" val="0">2016-09-16</span> | 
<span class="dateStart" val="1">2016-09-15</span> |
<br/><br/>
<button onclick="getSelected()">Click Here</button>