44

I have several objects on a page and I want to perform an operation using jQuery only on some of them - the ones that don't have a specified attribute. So:

<li style='...'>some text</li>
<li style='...'>some other text</li>
<li>some very diffrent text</li>

and in javascript I would have:

$('li[style]').hide();

that would hide all elements with a style sttribute. But if I want to hide the ones without it, how should my selector look like?

4 Answers 4

84
jQuery("li:not([style])").hide();
Sign up to request clarification or add additional context in comments.

1 Comment

Very simple, on one line... perfect answer!
5

You can use the :not psuedo-selector to look up elements that don't match a certain selector. In your example, you want to select all li elements without the style attribute, so you'd use something like this:

$('li:not([style])').hide();

You can also combine this with other selectors:

$('#div input:not(:checked)').show();

It's a pretty powerful tool!

Comments

1

Try:

$('li:not([style])').hide();

Comments

1

You may find it clearer and more performant to use the .not() method instead of the selector. As an example:

$('li').not('[style]').hide();

This is also what the jQuery devs recommend.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.