jQuery text attribute selector
I am trying to use the text attribute as a selector, but I can't quite grasp the behavi开发者_JS百科our, would really appreciate if someone could explain. For example given <span class="span_class"><a class="a_class">text</a></span>
, $('a.a_class').text()
gives "text" as expected. However $('a.a_class[text]')
wouldn't match any elements, and neither would $('span.span_class > a.a_class[text]')
, but $('span.span_class* > a.a_class[text]')
would (although not in IE).
The only workaround I can think of for IE, is loop through all anchors contained in a span, use .text() on each and match it against a certain criteria, but it seems slower than using in-built selectors. Anyone have better ideas?
what about using a custom selector
$(document).ready(function(){
$.extend($.expr[':'], {
notext: function(elem, i, attr){
return( $(elem).text() === "" );
}
});
});
Synopsis
$('span:notext').remove();
you might even want to create a selector that handles Regular Expressions like
$.extend($.expr[':'], {
'content': function(elem, i, attr){
return( RegExp(attr[3]).test($(elem).text()) );
}
});
Synopsis
$('span:content(^api_)').remove();
would select and remove all spans which text begins with api_
This is because 'text' in this case is not an attribute. It is the content of the element.
You're looking for the :contains()
selector:
$('a.a_class:contains(text)');
http://api.jquery.com/contains-selector/
Keep in mind that this selector will match any part of the string. contains(foo)
will match "foo bar" as well.
If you want an exact match of the entire text string, you could use filter()
$('a.a_class').filter(function() {
return $(this).text() == "text";
});
EDIT:
To find elements whose content starts with a value, you could use a regular expression inside the filter()
:
$('a.a_class').filter(function() {
return $(this).text().indexOf( "tex" ) >= 0;
});
EDIT: Updated to use indexOf()
instead of regex as recommended by @Nick.
精彩评论