jsv jsv - 6 months ago 10
jQuery Question

Search duplicate IDs with some class name

This function will find and alert about all duplicate custom attributes (for example, if you would try to use

foo
instead of default
id
).

function duplicateAttrChecker() {

var parmName = "foo";
$("["+parmName+"]").each(function(){
var value = $(this).attr(parmName);
if($("["+parmName+"='"+ value + "']").length > 1) {
console.log('duplicate', parmName, 'for value', value);
}
});

}


The full code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

<p foo="one">hello</p>
<p foo="three">hello</p>
<p foo="one">hello</p>

<script>
function duplicateAttrChecker() {

var parmName = "foo";
$("["+parmName+"]").each(function(){
var value = $(this).attr(parmName);
if($("["+parmName+"='"+ value + "']").length > 1) {
console.log('duplicate', parmName, 'for value', value);
}
});

}

duplicateAttrChecker();
</script>


How may it be modified to find duplicates only with some class?

So, it should work like "search all elements with class
bar
and tell me is there are duplicate
foo
s among them"
.

Answer

You can prepend your class to the attribute selector:

function duplicateAttrChecker(className, attrName) {
    $("."+className+"["+attrName+"]").each(function() {
        var value = $(this).attr(attrName);
        if ($("."+className+"["+attrName+"='"+ value + "']").length > 1) {
            console.log('duplicate', attrName, 'for value', value);
        }
    });
}

duplicateAttrChecker('bar', 'foo');

This will search for all bar class elements and notify when they have duplicate foo attribute values.

The working jsFiddle can be found here: https://jsfiddle.net/mgaskill/y6ac86a4/

Comments