开发者

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

开发者 https://www.devze.com 2022-12-22 19:40 出处:网络
In trying to select elements that have any attributes, the following throws a jQuery syntax error. $(开发者_C百科\"div[*]\")

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

$(开发者_C百科"div[*]")

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

Tested with jQuery 1.3


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;})


You could create your own selector for no attributes:

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

$("div:noAttrs")


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;
})


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

0

精彩评论

暂无评论...
验证码 换一张
取 消