I'm trying to write a jquery selector that will select objects that have the same value for two of their attributes.
Something like this:
$('div[attr1=attr2]')
Given:
<div attr1="foo" attr2="bar">A</div>
<div attr1="bar" attr2="bar">B</div>
<div attr1="foo" attr2="bar">C</div>
<div attr1="foo" attr2="foo">D</div>
I want it to return links to the B and D divs.
Any thoughts?
You can do this with custom selectors with arguments.
$('div:attrEqual(attr1 attr2)')
You define the custom selector like this:
$.expr[':'].attrEqual = function(obj, index, meta, stack) {
var attrs = meta[3].split(" ");
return $(obj).attr(attrs[1]) == $(obj).attr(attrs[0]);
};
For performance, add [attr1][attr2]
to the selector so that the native DOM filters out nodes that don't have both attributes.
I think the attribute selector only allows you to compare with a constant value. But you can use the .filter()
function to do the comparison:
$('div[attr1][attr2]').filter(function(index) {
return $(this).attr('attr1') == $(this).attr('attr2');
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With