user3108268
user3108268

Reputation: 1083

If div value equals add class

If <div> has a value of e.g. Green then add class green.

HTML

<div>Green</div>
<div>Red</div>

CSS

.green {
  color: green;
}

jQuery

if ($("div").val() == "Green") {
    $("div").addClass("green");
}

Class should be added to div with Green and skipped for Red.

edit: added extra div.

Upvotes: 0

Views: 369

Answers (2)

Tushar Gupta
Tushar Gupta

Reputation: 15923

You need to check text() of div for your code to work. See code below.

Advice: I would also encourage you to add a class or an id to your elements and target your jQuery through them to avoid any unexpected changes

Example with one div

if ($("div").text() == "Green") {
  $("div").addClass("green");
}
.green {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Green</div>

Example with more than one div

$("div").each(function() {
  if ($(this).text() == "Green") {
    $(this).addClass("green");
  }
});
.green {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Green</div>
<div>Yellow</div>
<div>Green</div>

Upvotes: 3

Abhinash Majhi
Abhinash Majhi

Reputation: 507

Pure Vanilla Js if you need

let element = document.getElementsByTagName('div')[0]
let name = document.getElementsByTagName('div')[0].innerHTML
element.classList.add(name);
.green {
  color: green;
}
<div>green</div>

Upvotes: 1

Related Questions