Abe
Abe

Reputation: 23938

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

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?

Upvotes: 4

Views: 1683

Answers (5)

mdma
mdma

Reputation: 57717

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.

Upvotes: 7

Evan
Evan

Reputation: 835

use a double equals sign (==) to check for equality in an statement. single equals(=) is for assignment. So if($('div[attr1] == div[attr2]') { do something });

Upvotes: 0

meo
meo

Reputation: 31249

If i get you right, you want to know if any attribute has the same value, regardless of its name. You could do it like this:

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
    }
})

Upvotes: 1

Jess
Jess

Reputation: 8700

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 the 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>

Upvotes: 1

Laurent
Laurent

Reputation: 3837

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');
})

Upvotes: 5

Related Questions