Reputation: 11725
In the following, I want to remove class "item1" and add class item2 to maindiv. The code below is not working. What is wrong with the code and how do I include item2 in maindiv?
HTML:
<div class="item2"><a href="#" id="item2">item2</a></div>
<div class="maindiv">
<div class="item1"> <a href="#" id="item1">item1</a></div>
</div>
jQuery:
if (selection) {
if ($('.maindiv').hasClass('item1')) {
$('.maindiv').removeClass('item1').addClass('item2');
}
}
Upvotes: 0
Views: 89
Reputation:
You must have to target inner div like
$(document).ready(function() {
if(selection) {
$('.maindiv .item1').removeClass('item1').addClass('item2');
}
});
Upvotes: 1
Reputation: 129792
In your example, .maindiv
doesn't have a class named item1
, it has a
child that has that class. You're testing if it has it.
You may want to revise to something like:
if($('.maindiv > div').hasClass('item1')) {
$('.maindiv > div')
.removeClass('item1')
.addClass('item2');
}
Or
if($('.maindiv .item1').length > 0) {
$('.maindiv .item1')
.removeClass('item1')
.addClass('item2');
}
... whichever you find more readable.
Upvotes: 2
Reputation: 40
use id comparator for better solution like
item1<div class = "maindiv">
<div id="test" class = "item1" > <a href="#" id="item1">item1</a> </div>
</div>
if(selection)
{
if ( $('#test').hasClass('item1') ) {
$('#test').removeClass('item1').addClass('item2');
}
}
Upvotes: -1
Reputation: 38345
The .hasClass()
function checks that the element(s) it's being called on have that class (in your case it doesn't). It does not check that those elements contain an element with that class.
<div class="item1">
and <div class="item2">
are elements, not classes; item1
and item2
are classes on those elements. You seem to be confused about what a class is and what the .hasClass()
, .addClass()
and .removeClass()
functions do, so I'd suggest you go back and cover the basics.
Upvotes: 0