How I can do a foreach
or similar in jQuery? I need that when the user clicks in the <span>
, add the class inactive
to all <div>
s with the vote active
class in the <ul>
.
I've tried with the .each
method, but it doesn't work.
I have this HTML:
<ul class="suggestions inactive">
<li id="s2">
<div class="id">2</div>
<div class="vote inactive">
<span class="up"></span>
<span class="down"></span>
</div>
<div class="text">test2</div>
<div class="rating">2</div>
</li>
<li id="s3">
<div class="id">3</div>
<div class="vote active">
<span class="up"></span>
<span class="down"></span>
</div>
<div class="text">test3</div>
<div class="rating">0</div>
</li>
</ul>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="script.js"></script>
And this script:
$(document).ready(function(){
var ul = $('ul.suggestions');
// Listening of a click on a UP or DOWN arrow:
$('div.vote span').live('click',function(){
var elem = $(this),
parent = elem.parent(),
li = elem.closest('li'),
ratingDiv = li.find('.rating'),
id = li.attr('id').replace('s',''),
v = 1,
ul2 = elem.closest('li').parent();
// If the user's already voted:
if(parent.hasClass('inactive')){
return false;
}
if(ul2.hasClass('inactive')){
return false;
}
//If the user's already voted, add following class
parent.removeClass('active').addClass('inactive');
ul2.removeClass('active').addClass('inactive');
if(elem.hasClass('down')){
v = -1;
}
// Incrementing the counter on the right:
ratingDiv.text(v + +ratingDiv.text());
// Turning all the LI elements into an array
// and sorting it on the number of votes:
var arr = $.makeArray(ul.find('li')).sort(function(l,r){
return +$('.rating',r).text() - +$('.rating',l).text();
});
// Adding the sorted LIs to the UL
ul.html(arr);
// Sending an AJAX request
$.get('ajax.php',{action:'vote',vote:v,'id':id});
});
You don't need .each()
here at all.
Why? Because jQuery's selectors wonderfully select everything of a single selector type. $('p')
selects every p
in your HTML.
You should use
$(this).parent().addClass('active').removeClass('inactive');`
from within the scope of the
$('div.vote span').live('click',function() { ... } );
Also, remember that .live()
is deprecated in jQuery 1.7+.
Are you sure you really want to add that class to ALL elements in the HTML? If so, I guess I would just do this:
$("div").addClass("inactive");
You do not need each
for adding class to multiple elements. Just select them and apply addClass()
:
jQuery('div.vote.active').addClass('inactive');
If you insist on using .each()
, then it really works. Just use it properly:
jQuery('div.vote.active').each(function(){
jQuery(this).addClass('inactive');
});
Did it help?