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??
Using a
for...inconstruct 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 matchedlielements.If you use a normal
forloop (or, as others have noted, the jQueryeachmethod), it would work: