5

I'm modifying the CSS of an existing WordPress theme. The theme has a lot of special styles for lists, attached to the <li> element. Because of this, there is a generic list-style:none rule applied to the <li> element.

I want to update the CSS to reinstitute the list-style defaults on <li> elements that don't have a class attached (i.e. those that don't have a special style applied). This needs to be selective to keep from ruining the fancy effects.

I am aware of the :not() pseudo-selector, and may end up using it to specifically exclude each possible class; however, there are a dozen of them and this seems like a maintenance nightmare.

Is there any way, either using CSS or jQuery, to select an element by specifying that it has no class set?

3 Answers 3

8

$('li:not([class])'); should do what you need.

Considering Dan's comment - since you didn't specify I assumed you meant the li would have no class attribute at all. If you need to grab those that are <li class> or <li class="">...

$('li:not([class])');
$('li[class=]');
$('li[class=""]');
2
  • Does not select elements like: <li class></li> or <li class=""></li> Commented May 9, 2011 at 19:38
  • You're correct; I was thinking of <li>, with no class attribute at all. I appreciate the clarification! Commented May 11, 2011 at 2:01
2

jQuery: $('li[class=]') (selects both elements that have no class attribute as well as those for which the attribute is present, but empty)

The CSS selector li[class=""] unfortunately does not work the same way. It selects only those elements for which the attribute is present, but empty (ex: <li class></li> or <li class=""></li>)

The $('li:not([class])') solution might not be what you want (it doesn't select elements that have the class attribute present but empty).

Given:

<ul>
  <li>item 1</li>
  <li class>item 2</li>
  <li class="">item 3</li>
  <li class="some-class">item 4</li>
</ul>

$('li[class=]') selects 1,2,3
$('li[class=""]') selects 2,3
$('li:not([class])') selects just 1

1
  • Thanks for including examples. That makes the differences between the selectors very clear. Commented May 11, 2011 at 2:00
0

Interestingly, you can do it:

$('li[class=]')

or

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

K

Not the answer you're looking for? Browse other questions tagged or ask your own question.