Tinker
Tinker

Reputation: 319

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!

Upvotes: 2

Views: 1902

Answers (5)

Babu
Babu

Reputation: 127

If you want to loop through all the elements

$('ul li').each(function(){
var className = $(this).attr('class');
var content = $(this).text();

});

Upvotes: 1

rlemon
rlemon

Reputation: 17667

I have commented the code to better help you understand it.

$("#ul li").each(function() { /* you should only be using # selector to identify id's - if it's all ul's you want just put ul. */
    var klass = this.className; /* this refers to the native DOM object, which contains className */
    var textContents = this.innerText || this.textContent; /* the text of the list, does not include html tags */
    var childNodes = this.childNodes; /* the child nodes of the list, each unencased string of text will be converted into a TextNode */
    console.log(klass + ' ' + textContents); /* replace console.log with alert if you do not have a console */
    console.log(childNodes);
});

here is an example of the above.

Good Luck!

Upvotes: 0

Raynos
Raynos

Reputation: 169451

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
}

Upvotes: 2

Ry-
Ry-

Reputation: 225074

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.

Upvotes: 5

SLaks
SLaks

Reputation: 887807

The get() method returns a native array of DOM elements, not a jQuery object.

You should use jQuery:

var lists = $('ul li');

var className = lists.eq(i).attr('class');
var content = lists.eq(i).text();

Upvotes: 1

Related Questions