JQuery: Test if two jQuery objects point to the same HTML Element
April 17th, 2009 by jeremychoneLet’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>
October 13th, 2009 at 12:21 am
Is there a get() method in jQuery? I thought you used eq() to do that.
Shows what I know!
November 11th, 2009 at 5:02 pm
@alex, get(.) get the DOM Element, eq() get the JQuery object.
http://docs.jquery.com/Core/eq
http://docs.jquery.com/Core/get
May 5th, 2010 at 4:20 pm
thank you, your solutions helped with an annoyance.
July 14th, 2010 at 10:46 am
Thank you. This article helped me a lot. I especially like the difference between ‘get’ and ‘eq’.
September 21st, 2010 at 8:04 am
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], …];