/    Sign up×
Community /Pin to ProfileBookmark

How can i access every 5th Div?, in a container

Hey Everyone,
Here’s what i’m trying to do..

i have div that will contain numerous other div (products in a shopping cart), say
up 50.

of these contained divs, i need to access every 5th div begging with 1, so it’d be div # 1, 6, 11, 16, 21 etc. and then use jQuery to Add Class to these divs.

can someone point me in the right direction on how to do this?

it would be hugely appreciated, thanks

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@cpkid2Jan 22.2011 — This tutorial should help you.
Copy linkTweet thisAlerts:
@tirnaJan 22.2011 — This accesses the starting div and then every nth div after the starting div.

Replace the alert() with whatever you want to do with the div.


[code=html]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
window.onload=function(){
divsO = document.getElementById("container").getElementsByTagName('div');
var startDiv = 1, step = 3, count = 0;
for(i=startDiv-1; i < divsO.length; i++){
if(i == startDiv-1 || ++count == step) {
alert(divsO[i].innerHTML);
count = 0;
}
}
}
</script>
</head>
<body>
<div id="container">
<div>This is div 1</div>
<div>This is div 2</div>
<div>This is div 3</div>
<div>This is div 4</div>
<div>This is div 5</div>
<div>This is div 6</div>
<div>This is div 7</div>
<div>This is div 8</div>
<div>This is div 9</div>
<div>This is div 10</div>
</div>
</body>
</html>

[/code]
Copy linkTweet thisAlerts:
@toicontienJan 22.2011 — Or:
[CODE]jQuery("#container div").each(function(i, div) {
if (i === 0 || i + 1 &#37; 5 === 0) {
// do something
}
});[/CODE]
Copy linkTweet thisAlerts:
@toptomatoauthorJan 23.2011 — Thank you all very much! Truly appreciated,

I will try them all.
×

Success!

Help @toptomato spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...