MAZ
MAZ

Reputation: 214

How can I add a class to an element if the text is the same?

I have two different divs:

<div class="first-div">this is the same text</div>
<div class="second-div">this is the same text</div>

Is it possible to detect if the text in the both divs is the same, then add class to the second div?

<div class="second-div newclass">this is the same text</div>

Upvotes: 0

Views: 1202

Answers (3)

Nish
Nish

Reputation: 738

I created this small program to answer your question :

function myFunction() {
  var div1_text = document.getElementById("one").value;
  var div2_text = document.getElementById("two").value;
  if (div1_text == div2_text) {
    document.getElementById("two").classList.add("class2");
  }
}
.class2 {
  width: 100%;
  padding: 25px;
  background-color: coral;
  color: white;
  font-size: 25px;
  box-sizing: border-box;
}
<button onclick="myFunction()">Try it</button>

<div id="one" class="myDIV">
  This is a DIV element.
</div>
<div id="two" class="myDIV">
  This is a DIV element.
</div>

Upvotes: 1

Nino Filiu
Nino Filiu

Reputation: 18533

Yes, it is possible in pure JS, jQuery is not even needed:

const firstDiv = document.querySelector('.first-div');
const secondDiv = document.querySelector('.second-div');
if (firstDiv.textContent === secondDiv.textContent) {
  secondDiv.className += ' new-class';
}

Upvotes: 2

upender
upender

Reputation: 180

Yes it is possible

document.getElementsByClassName("second-div")[0].className="second-div newclass"

Upvotes: 0

Related Questions