Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does jQuery object contain?

let's say, i have this code:

<ul>
  <li><strong>list</strong> item 1 -
    one strong tag</li>
  <li><strong>list</strong> item <strong>2</strong> -
    two <span>strong tags</span></li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
  <li>list item 6</li>
</ul>

<script>
    var x = $("li");
    for (var k in x){
        alert(k + x[k]);
    }
</script>

The problem is: alert outputs too many things! Why? Why doesn't it output only li elements?? Where do li elements get stored?? How do i output only li elements to which jQuery methods usually applied??

like image 221
DrStrangeLove Avatar asked Jun 06 '26 07:06

DrStrangeLove


2 Answers

You can use the jquery each function.

$("li").each(function(index, el){
      ..
});

http://api.jquery.com/jQuery.each/

like image 192
VJAI Avatar answered Jun 08 '26 00:06

VJAI


Using a for...in construct will also iterate all properties, including all properties inherited through the prototype chain, which is why you get all the properties of the object alerted, as well as the set of matched li elements.

If you use a normal for loop (or, as others have noted, the jQuery each method), it would work:

var x = $("li");
for (var k = 0; k < x.length; k++){
    alert(k + x[k]);
}
like image 26
James Allardice Avatar answered Jun 07 '26 23:06

James Allardice