43

I'm writing a sortable list implementation in jQuery (b/c of the infamous scroll-in-div issue, any new solutions for this?). However, I don't know how to compare the elements (triggered on mousedown/mouseup) after they've been wrapped in jQuery. In prototype, it was always ele.domNode.

This is what I'm trying to accomplish in essence...

<div id="cheese"></div>
<div id="burger"></div>

<script>

// Some dom nodes wrapped in jquery
var ele1 = $('#cheese');
var ele2 = $('#burger');
var ele3 = $('#burger');

// Is the dom node wrapped in ele1 (#cheese) the same as in ele2 (#burger)?
if (ele1 == ele2)
{
    // Should never be true
}

// Is the dom node wrapped in ele2 (#burger) the same as in el32 (#burger)?
if (ele2 == ele3)
{
    // Should always be true
}

</script>
John Himmelman
  • 21,504
  • 22
  • 65
  • 80

3 Answers3

66

A jQuery object can be treated as an array of raw DOM elements.

You can compare the raw DOM elements like this:

if(ele2[0] === ele3[0])
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
14

Compare the DOM elements inside like this:

if (ele1.get(0) == ele2.get(0))
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
0

This is also a possible way to solve this problem. You can compare the id attributes since they should be the exact same in your example above.

ele1.attr("id") == ele2.attr("id"); //returns false
ele2.attr("id") == ele3.attr("id"); //returns true
M7Jacks
  • 124
  • 9
  • There is nothing gained from comparing by `id`, and calling `attr` is certainly slower than just indexing into jQuery objects. – Louis Oct 29 '14 at 22:00
  • Thanks for your insight. I just thought I'd share a solution that also works with no consideration for performance in comparison with other solutions since the OP did not say he was looking for the fastest solution. – M7Jacks Oct 30 '14 at 18:14
  • And it won't work if the elements have no id.. – Tofandel Mar 16 '19 at 19:12