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].
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].
Share Improve this question edited Feb 4, 2012 at 10:38 ziesemer 28.7k9 gold badges88 silver badges95 bronze badges asked Feb 4, 2012 at 10:35 Alex G.Alex G. 2772 gold badges5 silver badges14 bronze badges 3- 1 Do you have some sample code to share? Instead of adding the divs to an array you could use index() - api.jquery./index - or the ':eq' selector. – Sagar Patil Commented Feb 4, 2012 at 10:40
- 1 Why don't you use $("div.page:eq(2)") instead of building an array ? – Benoit Blanchon Commented Feb 4, 2012 at 10:42
- Thank you very much for the tip, came in handy! – Alex G. Commented Feb 4, 2012 at 23:07
4 Answers
Reset to default 5var pageDivs = document.getElementsByClassName("page");
for(i = 0; i < pageDivs.length;i++)
{
//apply your effects using pageDivs[i]
}
Do you want to do like this ?
<html>
<head>
<script src="http://ajax.googleapis./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>
I think in some of browsers getElementByClassName is not supported.However you can use calssName property like this :
function getElementsByClassName( strClassName, obj ) {
if ( obj.className == strClassName ) {
//insert this elm into array
array.push(obj);
}
}
.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.