views:

105

answers:

4

In trying to select elements that have any attributes, the following throws a jQuery syntax error.

$("div[*]")

Is there a selector to check if a tag has any attributes?

Tested with jQuery 1.3

+5  A: 

I don't think so but this should do the trick

$('*').filter(function(){return this.attributes.length;})

and the opposite:

$('*').filter(function(){return !this.attributes.length;})
Ariel Popovsky
A: 

Maybe if($('.class').attr('*:attr').length > 0)

c0mrade
The attr method can't do selections like that http://api.jquery.com/attr/
PetersenDidIt
+5  A: 

You could create your own selector for no attributes:

$.expr[':'].noAttrs = function( objNode  ){
    if (objNode.attributes.length) return( true );
    return( false );
}

$("div:noAttrs")
PetersenDidIt
+1  A: 

I went with Ariel Popovsky's suggestion to use filter, though if I needed this in many places, I would use petersendidit's suggestion of creating a customer selector.

The (important) difference is that the .specified property needs to be checked. IE always returns more than 80 attributes.

Note: even this is not 100%. There are some attributes, like INPUT .value, that are special cases, but since I'm using a DIV, I can ignore them.

$("div").filter(function()
{ 
    for (var i = 0; i < this.attributes.length; i++)
    {
        var attr = this.attributes[i];
        if (attr.specified) 
        {
            return true;
        }
    }
    return false;
})
Doug D