Reputation: 189
How can I replace this for-each loop with jQuery?
$(document).ready(function(){
hidebutton = $("#hideall");
hidebutton.click(function(){
for(i=1;i<=6;i++){
var countrylist = document.getElementById("Country-"+i);
countrylist.style.display = "none";
}
});
});
The HTML is
<input id="hideall" type="button" value='Hide Countries' /><br /><br />
<div id="Country-1">USA</div>
<div id="Country-2">UK</div>
<div id="Country-3">UAE</div>
<div id="Country-4">China</div>
<div id="Country-5">India</div>
<div id="Country-6">Japan</div>
Upvotes: 1
Views: 173
Reputation: 13549
Edited your jsfiddle, added an example of jQuery foreach in a comment. However, you don't need foreach here because jQuery can operate on a collection. I changed your HTML as well, you need to group those divs better:
<div id="Countries">
<div id="Country-1">USA</div>
<div id="Country-2">UK</div>
<div id="Country-3">UAE</div>
<div id="Country-4">China</div>
<div id="Country-5">India</div>
<div id="Country-6">Japan</div>
</div>
$(document).ready(function(){
hidebutton = $("#hideall");
hidebutton.click(function(){
$('#Countries div').hide();
// $('#Countries div').each(function(index, divElement) { ... });
});
});
Upvotes: 1
Reputation: 105029
As you may know jQuery supports CSS3 selectors whether browser does or doesn't. Hence you can use a more advanced selector that will select all elements with ID starting with Country
:
$('div[id^="Country"]').hide();
Upvotes: 4
Reputation:
try:
hidebutton.click(function(){
$('[id^="Country-"]').hide();
});
Note that will also hide any elements that happen to start with "Country-" that you don't want to hide, but assuming you don't have any of those, this will work.
Upvotes: 3
Reputation: 3556
give each country a class (i.e. "country"), then do $('.country').hide()
Upvotes: 0
Reputation: 887453
You can add a class to each of the elements (eg, class="Country"
), then write
$('.Country').hide();
Upvotes: 2