Reputation: 27
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
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
Reputation: 51
This will work for you:
$("#a1 #b1").removeClass("Green");
$("#a1 #b1").addClass("red");
Upvotes: 1
Reputation: 1861
$(divId).find
returns a jQuery object.
className
is a property of HTML Element in vanilla JavaScript.
You do one of the following
Upvotes: 1