1

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].

3
  • 1
    Do 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. Commented Feb 4, 2012 at 10:40
  • 1
    Why don't you use $("div.page:eq(2)") instead of building an array ? Commented Feb 4, 2012 at 10:42
  • Thank you very much for the tip, came in handy! Commented Feb 4, 2012 at 23:07

4 Answers 4

5
var pageDivs = document.getElementsByClassName("page");
for(i = 0; i < pageDivs.length;i++)
{
    //apply your effects using pageDivs[i]
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

0

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);
    }  
}

Comments

0

.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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.