Reputation: 16610
I have predefined css selectors list in js array and an element. I need to find which selectors would apply on that element.
Here is my code: http://jsfiddle.net/mjALF/
html
<div id="main">
<div class="a" id="d1">
<div class="b" id="d2">
<div class="c" id="d3">
</div>
</div>
</div>
<div class="b" id="d4"></div>
<div class="c" id="d5"></div>
</div>
js
var selectors = ['#main .a', '#main .a .b', '.a', '#main .c', '#main .a .b .c'];
// pseudo code
/*
find_selectors($('#d4'), selectors);
result: null
find_selectors($('#d1'), selectors);
results: ['#main .a', '.a'];
*/
Upvotes: 1
Views: 76
Reputation: 630569
You can use $.grep()
to get a filtered array with .is()
, like this:
var elem = $("#d1");
var results = $.grep(selectors, function(s) { return elem.is(s); });
You can test it out here. Or, as a plugin!
$.fn.selectorMatch = function(sArray) {
var elem = this;
return $.grep(selectors, function(s) { return elem.is(s); });
};
Then you can call it like this:
var results = $("#d1").selectorMatch(selectors);
You can test the plugin version out here.
Upvotes: 4