ultraloveninja
ultraloveninja

Reputation: 2139

jQuery Add Class if data value is true

I am trying to add a class to a div by checking to see if the current class contains a data-value of New. But I'm not 100% sure if I am structuring this the correct way:

if ($(".link").data("value") === 'New') {
  $(this).addClass('new');
}
<div class="link" data-value="New">
  <a href="">LINK</a>
</div>

Basically, if the data-value is New then add the new class to link

Not sure if that is correct or not.

Upvotes: 1

Views: 1774

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337626

The issue is because the if condition does not have the scope of the .link element, so this actually refers to the window.

To fix this you will need to select the .link element directly. Try this:

if ($(".link").data("value") === 'New') {
  $('.link').addClass('new');
}
.new {
  border: 1px solid #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="link" data-value="New">
  <a href="">LINK</a>
</div>

Also note that this will only work for a single instance of the .link class. You'll need to loop through each one individually if there are multiple elements with that class. Which you can do like this:

$('.link').each(function() {
  if ($(this).data("value") === 'New') {
    $(this).addClass('new');
  }
});
.new {
  background-color: #CC0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="link" data-value="New">
  <a href="">LINK</a>
</div>

<div class="link">
  <a href="">LINK</a>
</div>

<div class="link" data-value="New">
  <a href="">LINK</a>
</div>

Upvotes: 3

Related Questions