Reputation: 219
I have the following array, which are elements within a html page:
["1", "1", "1","2", "2", "2","3", "3", "3","4", "4", "4",];
More specifically these are divs:
<div class="abc1">1</div>
<div class="abc2">1</div>
<div class="abc3">1</div>
<div class="abc4">2</div>
<div class="abc5">2</div>
<div class="abc6">2</div>
<div class="abc7">3</div>
<div class="abc8">3</div>
<div class="abc9">3</div>
<div class="abc10">4</div>
<div class="abc11">4</div>
<div class="abc12">4</div>
I want to hide the 1st, 3rd, 4th, 6th, 7th, 9th, 10th, 12th div.
I tried this code but it only hides every odd number.
$(document).ready(hideLabelFF);
function hideLabelFF(){
$('*[class^="abc"]').each(function (i){
$('*[class^="abc"]:nth-of-type(2n+1)').hide();
});
};
Upvotes: 1
Views: 197
Reputation: 24522
I'm not sure what the purpose of this action is; sounds like a homework assignment to find the smartest way to do this.
The most straightforward way would be this:
[1, 3, 4, 6, 7, 9, 10, 12].forEach(num => $(`.abc${num}`).hide());
It's not smart though. You've already noticed a pattern there. The shown elements are 2, 5, 8, 11, i.e. 3n-1. You can therefore do this:
$('*[class^="abc"]:nth-of-type(3n-2)').hide();
$('*[class^="abc"]:nth-of-type(3n)').hide();
inverse the hiding:
$('*[class^="abc"]').hide();
$('*[class^="abc"]:nth-of-type(3n-1)').show();
or finally, use the .not()
method to bring this all to a one-liner:
$('*[class^="abc"]').not(":nth-of-type(3n-1)").hide();
Upvotes: 1
Reputation: 28475
With 2n+1, you are targetting odd divs. You have 2 series one is 1,4,7,10... and the other is 3,6,9,12...
Simply try following
function hideLabelFF(){
$('*[class^="abc"]:nth-of-type(3n+1)').hide();
$('*[class^="abc"]:nth-of-type(3n)').hide();
}
For reference - plunker
Upvotes: 3