How can I select an element only if it doesn't have a class assigned?
I'm modifying the CSS of an existing WordP开发者_开发问答ress 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?
$('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=""]');
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
Interestingly, you can do it:
$('li[class=]')
or
$('li:not([class]=)')
K
精彩评论