简体   繁体   中英

How to check if class attribute exist?

I'm trying to check if there is no class tag within a <li> </li> tag.

For example, if I have this:

<li class="menu...."> words </li> 

I want to ignore it. However if I have this:

<li> words </li> 

I want to use it.

What I currently have is something along the lines of:

$("li").each(function() {
    if ($(this).classList.contains('') {
        do function
    }
})

However, this is not working - how would I go about doing this?

Thanks in advance

$('li:not([class])');

This will select all li elements without a class at all. You can replace [class] with a specific class as well, or use hasClass .

You can do this:

$("li:not(.menu)").whatever();

That's not the fastest way necessarily; it may be faster to do this:

$("li").filter(function() { return !$(this).hasClass("menu"); }).whatever()

edit if you want to operate on <li> elements that have no class, then just check the .className property:

$("li").filter(function() { return !$(this).prop("className"); }).whatever()

However, I would suggest that that's not a good coding pattern. It's fragile because it relies on any future changes to your page for purposes completely unrelated to what you're doing now not involving the addition of a class. You'd be better off explicitly checking for specific classes that you're not interested in.

Like, maybe 3 months from now, somebody decides that all the list items that are about penguins be made black and white. You then add the class "penguin" to all those <li> elements. If you don't remember this change you're making now, all of a sudden that functionality will be broken.

You can use prop()

$("li").each(function() {

    if (!$(this).prop("class")) {

        doFunction();
    }
});

DEMO

The classList is only available on Element instances, not on the jQuery object.

$("li").each(function() {
  if (this.classList.length === 0) {
    do function
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM