Create array of elements with same class

0 votes
asked Jun 7, 2013 by user2232681

Would this be an acceptable method of creating an array of

elements having the same class, or is there something more efficient?
<ul>
  <li  class="show" id="all">All Posts</li>
  <li  class="show" id="user" data-user="7">My Posts</li>
  <li  class="show" id="follow">Following</li>
</ul>

$(document).ready(function() {
  var newarr=[];
  $("li").click(function(event) {
    var name = event.target.className;
    var newclass = 'choice';

  $(this).addClass(newclass);
  $(this).siblings().removeClass(newclass);

  $('li[class~=' + newclass + ']').each(function(index) {
    var thisid = $(this).attr('id');
    newarr[index] = thisid;
    })

  $.each(newarr,function(index,value) {
    //console.log(index + value);
        })

    });
});

2 Answers

0 votes
answered Jun 7, 2013 by justin-bicknell

I would use the map function to create the array:

var newarr = $('li[class~=' + newclass + ']').map(function(){ 
                 return $(this).attr('id');
              });
0 votes
answered Jun 7, 2013 by nl-x

im guessing newarr[index] = thisid; should just be newarr[] = thisid;.

but then again i dont even think i understand what you want to do.

why are you working from the .click handler?

on each click you set newclass to the clicked item and add it to the array. but you also remove the newclass from the siblings, so the previously clicked items will lose the newclass again... so in newarr only the last clicked item will have newclass

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...