Jquery intersect selector
I'm sure the answer exists on SO somewhere, but I'm at a loss for what terminology to search for. So apologies if this is a duplicate.
Is there an easy way in jQuery/JS of selecting the elements that "intersect" from the following HTML?
<div id="first">
<div id="source-AAA"/>
<div id="source-CCC"/>
<div id="source-EEE"/>
<div id="source-FFF"/>
</div>
<div id="second">
<div id="BBB"/>
<div id="CCC"/>
<div id="DDD"/>
<div id="FFF"/>
</div>
i.e. getting hold of the elements #CCC
and #FFF
from div#second
, based on the fact that these two IDs are in #first
?
I guess the proper answer is to do the intersect开发者_如何学C on the server-side (which is possible, but painful, as the two data sets come from different components), but I thought I'd check in case anyone knows of a neat way to do it in jQuery?
You'll first have to collect all those IDs, and then build up a CSS selector string accordingly:
var divsToSelect = [];
$('#first div').each(function(){
divsToSelect.push( $(this).attr('id').substr(-3) );
});
$('#' + divsToSelect.join(',#'));
http://jsfiddle.net/TXqw3/
You could use filter -
$("#second div").filter(function() {
return $("#first > div[id$=" + this.id + "]").length > 0
})
Demo - http://jsfiddle.net/b9NZR/
Why not clientside?
$('div#first > div').each(function(){
var fv = $(this).attr('id');
$('div#second > div').each(function(){
var sv = $('div').attr('id');
if (fv.indexOf(sv) > -1){
// do something
}
});
});
Of course am no expert but something along the line.
精彩评论