Maxim Gershkovich
Maxim Gershkovich

Reputation: 47229

Determine if two HTML elements are different without ID

If you take away the ID property (IE: Assume its never been set) of any given HTML element (or more specifically a checkbox) is there a way that I can determine if I have two references to the same element?

Basically I am trying to get the following code working but dont think I can do it without the id attribute set.

The checkboxes are declared as such (So I can't use the id property)

<input type="checkbox" class="RowSelector" />

And here is the method I am trying to create

$(function () {
    $(".RowSelector").click(function (e) {
        var current = this;
        $(".RowSelector").each(function (index, value) {
            if (current != value) { //This doesnt work but is there a way I can make it?
                $(value).prop("checked", false);
            }
        });
    });
});

So is it possible using JavaScript to determine if I have two references to the same HTML element?

Upvotes: 3

Views: 152

Answers (1)

jfriend00
jfriend00

Reputation: 708176

You can let jQuery do the work for you in a lot less code:

$(function () {
    $(".RowSelector").click(function (e) {
        $(".RowSelector").not(this).prop("checked", false);
    });
});

or a little more efficiently:

$(function () {
    var rows = $(".RowSelector").click(function (e) {
        rows.not(this).prop("checked", false);
    });
});

In case you're interested in the answer to your other question (which is now handled for you by jQuery in the above code), you can directly compare two DOM references. They will be == if and only if they refer to the same DOM node.

Upvotes: 3

Related Questions