Reputation: 171
I am using jQuery's $.each()
method to iterate through all DOM elements that are members of a certain class (e.g. class="definition"
) and then print each element's ID to the console. However, the iteration only seems to work on elements for which the specified class is defined first. Therefore, for elements with multiple classes, if the specified class is not listed first in the HTML, it appears to be "skipped".
For example:
HTML
<p class="definition" class="snippet" id="P1">Paragraph 1</p>
<p class="open" class="definition" class="snippet" id="P2">Paragraph 2</p>
<p class="snippet" class="definition" id="P3">Paragraph 3</p>
<p class="definition" class="snippet" id="P4">Paragraph 4</p>
<p class="definition" id="P5">Paragraph 5</p>
JavaScript
$( document ).ready(function() {
$(".definition").each(function() {
console.log(this.id);
});
});
In the above example, the console logs the IDs for P1, P4, and P5 but not the others.
Is there a reason that the typed order by which the classes are defined should determine whether or not jQuery's $.each()
recognizes the element by class?
Upvotes: 0
Views: 71
Reputation: 4387
Use
<p class="definition snippet" id="P1">Paragraph 1</p>
instead.
When you set the class property for second time, it rewrites the first one.
This:
<p class="definition" class="snippet" id="P1">Paragraph 1</p>
is the same as
<p class="snippet" id="P1">Paragraph 1</p>
You can also check the real html code using the console.
Upvotes: 5