jQuery: Select all p elements with some attribute set
I'm in the need for a jque开发者_如何转开发ry selector to get all p elements that has some attribute set, no matter the value and no matter the attribute name.
XPath related expression is:
"//p[@*]"
If you're saying that you want <p>
elements that have at least one inline attribute set, you could do this:
Example: http://jsfiddle.net/ZRPv4/
var pWithAttrs = $('p').filter(function() {
return this.attributes.length;
});
This will give you a set of <p>
elements that have at least one inline attribute set.
It tests the length
property of the attributes
array associated with the current <p>
in the iteration. If the length
is 0
, it will be removed from the result.
Here's a custom selector version:
Example: http://jsfiddle.net/ZRPv4/1/
$.extend($.expr[':'], {
'hasAnAttr': function(elem, i, attr){
return elem.attributes.length;
}
});
var pWithAttrs = $('p:hasAnAttr');
You must build the selector string as follows:
If you have an array of attribute names and values attrs
:
var selector = 'p';
for (var attrName in attrs) {
selector = selector + '[' + attrName + '=' + attrs[attrName] + ']';
}
}
This will create a selector string of the form:
p[attrName0=attrValue0][attrName1=attrName1] ...
and then use that selector in a jQuery statement:
$(selector).remove();
I don't think you can do that using expressions, but you can loop through the p elements and check for those that have attributes:
$('p').each(function(){
if(this.attributes.length > 0)
{
...do code...
}
});
$("p").each(function(){
if(this.attributes.size>0){
}
});
I dont know if is exist a pure jquery solution.
精彩评论