I want to insert all divs which have the class .page into an array, then call each using the array iteration. For example the array pages[] should allow me to add certain effect to the div in pages[2].
-
1Do you have some sample code to share? Instead of adding the divs to an array you could use index() - api.jquery.com/index - or the ':eq' selector.Sagar Patil– Sagar Patil2012-02-04 10:40:01 +00:00Commented Feb 4, 2012 at 10:40
-
1Why don't you use $("div.page:eq(2)") instead of building an array ?Benoit Blanchon– Benoit Blanchon2012-02-04 10:42:06 +00:00Commented Feb 4, 2012 at 10:42
-
Thank you very much for the tip, came in handy!Alex G.– Alex G.2012-02-04 23:07:59 +00:00Commented Feb 4, 2012 at 23:07
Add a comment
|
4 Answers
Do you want to do like this ?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var arr=[];
$(".page").each(function(){ arr.push($(this));});
$.each(arr,function(key,val){ val.css('color','gray')});
});
</script>
</head>
<body>
<b>.page content will be colored in gray.</b><br/><br/>
<div class="dontDo">The quick </div>
<div class="page">brown fox jumps</div>
<div class="doIt"> over the lazy dog</div>
<div class="page"> over the lazy dog</div>
</body>
</html>
Comments
.getElementsByClassName is not supported < IE8. If you aren't worried about that, then Sunil's response will work for you.
If you want the jQuery way:
$(".page").each(function(index) {
// do stuff here
});
Happy iterating.