JQuery: Test if two jQuery objects point to the same HTML Element

April 17th, 2009 by jeremychone

Let’s say you want to test if two JQuery objects represent the same HTMLElement. Comparing the JQuery objects will always return false since a new wrapper object is created at each new invocation.

So, use the $().get(0) to get the source HTML Dom Element (obviously, assuming the query was only for one element).

<ul>
<li><a onclick="clickHandle(event)">menu 1</a></li>
<li><a onclick="clickHandle(event)">menu 2</a></li>
</ul>

In your JavaScript:

<script type="text/javascript">
var previousLi = null;
function clickHandle(e){
  var e = $.event.fix(e); //fix the event (IE again)
  var clickedLi = $(e.target).closest("li");//get the closest parent li
  //now compare the HTMLElement not the jQuery objects.
  if (previousLi != null && previousLi.get(0) === clickedLi.get(0)){
    alert("aha, same li clicked");
  }
  alert("this will always return false: " + (previousLi === clickedLi));
  // update the previous Li
  previousLi = clickedLi;
}
</script>

5 Responses to “JQuery: Test if two jQuery objects point to the same HTML Element”

  1. alex Says:

    Is there a get() method in jQuery? I thought you used eq() to do that.

    Shows what I know!

  2. jeremychone Says:

    @alex, get(.) get the DOM Element, eq() get the JQuery object.

    http://docs.jquery.com/Core/eq

    http://docs.jquery.com/Core/get

  3. v Says:

    thank you, your solutions helped with an annoyance.

  4. Zimscoop Says:

    Thank you. This article helped me a lot. I especially like the difference between ‘get’ and ‘eq’.

  5. Lathan Says:

    The .get() method works, but there are alternatives:

    var object = $(’.someClass’);

    object.get(0) == object[0]

    The .get is also useful for returning a list of htmlElements
    object.get() == [ [object HTMLDiv], [object HTMLDiv], …];

Leave a Reply