2

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

Huangism
  • 15,899
  • 5
  • 47
  • 67
Rekovni
  • 4,984
  • 3
  • 34
  • 50

4 Answers4

6
$('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.

Sterling Archer
  • 21,348
  • 17
  • 79
  • 113
4

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.

Pointy
  • 389,373
  • 58
  • 564
  • 602
  • It's just an example, see the first line in the description. By tag I am sure OP means attribute – Huangism Sep 17 '14 at 20:33
  • @Huangism yes I see. I explained in my update that that's probably an anti-pattern to be avoided. – Pointy Sep 17 '14 at 20:34