Dar
Dar

Reputation: 27

How to replace the entire class within the element in HTML?

I have a HTML like the below,

var divId = document.getElementById('a1');
$(divId).find('#b1').className = "red";
.green {
  background-color: green;
  color: #ccc;
}

.red {
  background-color: red;
  color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="a1">
  <button id="b1" class="green">green</button>
</div>

<div id= "a2">
  <button id ="b2" class="red">red</button>
</div>

How to replace the class Green with class red ?

Upvotes: 0

Views: 523

Answers (3)

Mamun
Mamun

Reputation: 68933

You are mixing up jQuery and JavaScript here.

You can use className in a JavaScript referenced element. To change the class of a jQuery referenced element you should use .addClass(). Also, since the attribute id is unique in a DOM, simply specifying the id in the selector is enough.

$('#b1').addClass('class', 'red');

jQuery Solution:

$('#b1').addClass('red');
.Green {
  background-color: green;
  color: #ccc;
}
.red {
  background-color:red;
  color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id= "a1">
    <button id ="b1" class = "Green">Green</button>
</div>

<div id= "a2">
    <button id ="b2" class = "red">Red</button>
</div>

JavaScript Solution: Instead of using className, I will suggest you to use DOMTokenList.add() to add/remove class to an element.

var divId = document.getElementById('b1');
divId.classList.add('red');

var divId = document.getElementById('b1');
divId.classList.add('red');
.Green {
  background-color: green;
  color: #ccc;
}
.red {
  background-color:red;
  color: #fff;
}
<div id= "a1">
    <button id ="b1" class = "Green">Green</button>
</div>

<div id= "a2">
    <button id ="b2" class = "red">Red</button>
</div>

Upvotes: 2

angelsotiris
angelsotiris

Reputation: 51

This will work for you:

$("#a1 #b1").removeClass("Green");
$("#a1 #b1").addClass("red");

Upvotes: 1

Nice Books
Nice Books

Reputation: 1861

$(divId).find returns a jQuery object.

className is a property of HTML Element in vanilla JavaScript.

You do one of the following

  • the jQuery prop method, to set a property on a jQuery object.
  • the jQuery addClass method, to add a class on a jQuery object.
  • convert the jQuery object to an Element (see SO answer)
  • bypass jQuery itself & use querySelector instead.

Upvotes: 1

Related Questions