ttmt
ttmt

Reputation: 4984

Push li into jQuery array

I have a simple "ul" list

    <ul class="home>
      <li><a href="#"><img src"image1.jpg" /></a></li>
      <li><a href="#"><img src"image2.jpg" /></a></li>
      <li><a href="#"><img src"image3.jpg" /></a></li>
      <li><a href="#"><img src"image4.jpg" /></a></li>
      <li><a href="#"><img src"image5.jpg" /></a></li>
    </ul>

I would like to add each "li" and it's contents to an array.
I thought I could do like this but I don't think it's working.

    jQuery(function($){

        var imgArr = [];

        $('.home li').each(function(){
            imgArr.push(this);
            alert(imgArr);
        })

    });

How can I add each "li" to an array? How can I display the array to see it's contents?

Upvotes: 1

Views: 2927

Answers (1)

Gurpreet Singh
Gurpreet Singh

Reputation: 21233

Your HTML class name is not valid (missing double quotes), therefore your jquery selector is not working. Following JS will give you an array of LI's in console.

   jQuery(function(){

        var imgArr = [];

        $('.home li').each(function(){
            imgArr.push(this);
        })

         console.log(imgArr);   
    });​

DEMO

Upvotes: 3

Related Questions