I have used the hasClass method before but I have a scenario where is reporting as not been present although if I output the elements .html() it clearly shows the class is in use by item aswell as other classes.
The element that the class belongs too was dynamically written to the screen. Any ideas what I'm doing wrong?
$('.myList').each(function (index, item) {
// Check marked as complete
if (!$(item).hasClass('complete')) {
// Not complete
alert('not complete!' + $(item).html());
completeFlag = false;
return false;
}
});
The html output:
开发者_开发问答<li id="myid" class="class1 class2 complete">some text</li>
I'm guessing you're checking the list, where you mean to be checking the list items.
Example of what I think you're doing:
HTML:
<ul class="myList">
<li>This is not complete</li>
<li>Nor this</li>
<li class="class1 class2 complete">But this is</li>
<li>And this isn't</li>
</ul>
JavaScript:
$('.myList').each(function (index, item) {
// Check marked as complete
if (!$(item).hasClass('complete')) {
// Not complete
display('Item not complete: ' + $(item).html());
}
else {
// Is complete
display('Item IS complete: ' + $(item).html());
}
});
Live copy (which doesn't work)
Here's how you'd check the items: Change
$('.myList').each(function (index, item) {
to:
$('.myList li').each(function (index, item) {
// ^--- Note that we're now looping the
// list *items*, not the list
Live copy
.hasClass()
checks the specific element that matches your selector. You seem to be thinking it searches inside the element to see if the class is used there. That’s not how it works.
Is it that one of the child elements in your html have the class but the actual item itself does not? I believe that .hasClass()
only determines whether the actual element itself has the css class applied.
精彩评论