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??
You can use the jquery each function.
$("li").each(function(index, el){
..
});
http://api.jquery.com/jQuery.each/
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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With