Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list elements and its classes using jquery

I used $('#ul li').get() to get all the list elements and stored in an array, each of this list elements have classes...

var i;
var listClass = ('#ul li').get();
for(i=0;i<listClass.length;i++){
    var theClass = listClass[i].attr("class"); //<--what's the proper function/method/code for this?
    var content = listClass[i].innerHTML; //<-- works very well

    //other codes here
}

How may i able to get the classes of each list elements...Thanks!

like image 937
Tinker Avatar asked Apr 27 '26 19:04

Tinker


2 Answers

You can use jQuery's own map to do that:

alert($('#ul li').map(function() {
    return this.className;
}).get());

http://jsfiddle.net/MhVU7/

for example. You can do anything with the returned array.

The reason the way you're doing it isn't working is because you're calling the non-existent method .attr on a native DOM element - it's not an extended jQuery object.

like image 197
Ry- Avatar answered Apr 29 '26 11:04

Ry-


var lis = document.getElementById("ul").children;
for (var i = 0, len = lis.length; i < len; i++) {
  var li = lis[i],
      className = li.className,
      value = li.value,
      text = li.textContent;

  // code
}
like image 44
Raynos Avatar answered Apr 29 '26 10:04

Raynos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!