Jquery adding and removing class dynamically
I am trying to add the class"selected" when a link is clicked and when the user click on the next link , I want to remove the previously "selected" class and add "selected" to the link clicked..
-Thanks in advance
$(document).ready(function() {
$('.news a').click(function(){
$(this).addClass("selected");
});
});
<div class="news-w">
<div class="news" id="getnews-1">
<a href="#" >topic</a>
</div>
<d开发者_StackOverflow中文版iv class="news" id="getnews-2">
<a href="#">topic</a>
</div>
<div class="news" id="getnews-3">
<a href="#" >topic</a>
</div>
<div class="news" id="getnews-4">
<a href="#">topic</a>
</div>
<div class="news" id="getnews-5">
<a href="#">topic</a>
</div>
</div>
$(document).ready(function() {
$('.news a').click(function(){
$('.selected').removeClass('selected')
$(this).addClass("selected");
});
});
To add a toggle effect when adding a class or an ID, Use this.
$(document).ready(function() {
var count = 1;
$('#ddown').click(function(){
count++;
if (count % 2 == 0) {
$('#ddown').addClass('dropup');
$('#ddown').removeClass("dropdown");
}else{
$('#ddown').removeClass("dropup");
$('#ddown').addClass("dropdown");
}
});
});
Yea i know, I came to the party very late.
Try
$(document).ready(function() {
$('div.news-w div.news a').click(function(){
$('div.news-w div.news a.selected').removeClass("selected");
$(this).addClass("selected");
});
});
Also you are having an invalid HTML. You have more than 1 element with the same ID.
Another alternate solution is:
var prevLink = null;
$(document).ready(function() {
$('.news a').click(function(){
if(prevLink) prevLink.removeClass('selected');
prevLink = $(this).addClass("selected");
});
});
You can use this:
$('.news a').click(function(){
$('.news-w').find('.selected').removeClass('selected');
$(this).addClass("selected");
});
it will be removed automatically just class selected in div class='news-w'
If u use this :
$('.selected').removeClass('selected');
when u want to add more element a into DOM out from div class='news-w' it will be removed too..
精彩评论