I have a series of <div/>
's as follows:
<div>.co.uk</div>
<div>.com</div>
<div>.gb.com</div>
<开发者_如何学编程;div>.uk.com</div>
<div>.net</div>
How do I select just the divs containing .co.uk
, .com
, .net
.
If I use:
$('div:contains(".co.uk"), div:contains(".com"), div:contains(".net")`)
This causes the .gb.com
and .uk.com
divs to be selected as well.
You can use the filter
method to check the content:
$('div').filter(function(){
var t = $(this).text();
return t == '.co.uk' || t == '.com' || t == '.net';
})
You might still want to weed out as many elements as possible in the selector to reduce the number of elements that the filter function has to check. Even if the contains
pseudo class can't make an exact match, it can still be used to reduce the result:
$('div:contains(".co.uk"), div:contains(".com"), div:contains(".net")`).filter(function(){
var t = $(this).text();
return t == '.co.uk' || t == '.com' || t == '.net';
})
Your best bet is to iterate through the divs with .each()
and check for the contents in the callback by checking $(this).text()
:
$('div').each(function() {
if ($(this).text().match(/^\.(com|net|co\.uk)$/)) {
// ...
}
});
I'd do it with a filter:
jQuery.fn.pickDomains = function() {
var domains = jQuery.makeArray(arguments);
return this.filter(function(_, element) {
for (var d = 0; d < domains.length; ++d)
if (domains[d] == $(element).text()) return true;
return false;
});
};
Then you can just say something like:
var theDivs = $('div.whatever').pickDomains('.co.uk', '.com', '.net');
I was facing that problem, too, several times, especially since I was developing in Prototype where a StartsWith function exists. There's probably only the way of looping through divs and checking for substrings, code can be found on previous similar question.
精彩评论