How can I get the elements without a particular attribute by jQuery

Viewed 37330

I know how to get elements with a particular attribute:

$("#para [attr_all]")

But how can I get the elements WITHOUT a particular attribute? I try

 $("#para :not([attr_all])")

But it doesn't work. What is the correct way to do this?

Let me give an example:

<div id="para">
    <input name="fname" optional="1">
    <input name="lname">
    <input name="email">
</div>

jQuery:

$("#para [optional]") // give me the fname element  
$("#para :not([optional])") //give me the fname, lname, email (fname should not appear here)  
7 Answers

First thing that comes to my mind (maybe sub optimal) :

$('p').filter(function(){
    return !$(this).attr('attr_all');
});

However p:not([attr_all]) should work, so I think something else is going on in your code.

Looking at CSS3 selectors documentation the correct to select a node “node” without an attribute “attr” is:

<node>:not(<node>[<attr>])

E.g.: p:not(p[align])

In your case $("#para *:not([optional])") works, and could be more precise.

The actual syntax of ":not" is:

<selector1>:not(<selector2>)

There are two selectors in this expression, which selects all the nodes matching seletor1 then excludes all nodes matching selector2.

I would use:

$('#para input:not(input[optional])')

    /* or */

$('input:not(input[optional])',$('#para'))

    /* in case jQuery has issues with :not */

$( document.querySelectorAll('#para input:not(input[optional])') )

Finding the image tags with the no alt attribute or empty alt tag.

$('img').each(function( index ) {
    if(typeof $(this).attr('alt') === typeof undefined || $(this).attr('alt') === false ||$(this).attr('alt') === '') {
        console.log(index);
    }
});
Related