Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use jquery to check if two attributes have the same value?

Tags:

jquery

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?

like image 340
Abe Avatar asked Dec 10 '22 06:12

Abe


2 Answers

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.

like image 182
mdma Avatar answered Dec 15 '22 01:12

mdma


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');
})
like image 28
Laurent Avatar answered Dec 15 '22 01:12

Laurent