Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!