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

I am trying to write a jquery selector that will select objects that have the same value for two of their attributes.

Something like that:

$('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 B and D divs.

Any thoughts?

+4
source share
5 answers

You can do this with custom selectors with arguments .

 $('div:attrEqual(attr1 attr2)') 

You define a custom selector as follows:

 $.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 do not have both attributes.

+7
source

I think the attribute selector only allows comparing with a constant value. But you can use the .filter() function to compare:

 $('div[attr1][attr2]').filter(function(index) { return $(this).attr('attr1') == $(this).attr('attr2'); }) 
+4
source

Something like this would do the trick ( The Fiddle ):

 function GetWithSameAttributes (parID) { var output = new Array(); $('#'+parID).children().each(function () { if ($(this).is('[attr1="'+$(this).attr('attr2')+'"]')) output.push($(this).html()); }); return output; } $(function () { for (val in GetWithSameAttributes('Items')) document.writeln(val + ' has the same attributes<BR/>'); }); 

with html something like:

 <div id="Items"> <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> </div> 
+1
source

If you understand correctly, you want to know if any attribute has the same value, regardless of its name. You can do it as follows:

http://jsfiddle.net/zuwZh/2/

 $("div").filter(function(){ var attributes = this.attributes, i = attributes.length, attrValues = [], $that = $(this); if(i !== 1) { while( i-- ) { var attr = attributes[i]; attrValues.push(attr.value); } attrValues = attrValues.sort(); if(attrValues[0] === attrValues[1]) { return $that; //only checks between two attributes, but you could extend that } }) 
+1
source

use the double equal sign (==) to check for equality in the instruction. single equals (=) to assign. Therefore, if ($ ('div [attr1] == div [attr2]') {do something});

0
source

Source: https://habr.com/ru/post/1369051/


All Articles