Please have a look at the following code:
<HTML>
<HEAD>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<SCRIPT type="text/javascript">
function test(target) { alert(target.nodeName); }
</SCRIPT>
</HEAD>
<BODY>
<DIV>
<ul>
<li onclick="test(this)">This is fair</li>
<li onclick="test(this)">No its not</li>
<li onclick="test(this)">Why not</li>
<li onclick="test(this)">Becoz...</li>
</ul>
</DIV>
</BODY>
</HTML>
The function test receives target (li node) as an argument.
Now, can I somehow convert this variable to jQuery $(this) or $(e.target) or any other jQuery variable to so that I could traverse the document using the jQuery way?
Converting DOM element to jQuery object
To convert DOM element to jQuery object you do the following:
So, in your example it will be
$(this)or$(event.target)– depending on whether you want current element or the element that actually fired the event (in your case they are the same, unless event will be fired by some descendant element).Converting jQuery object to DOM element
To convert jQuery object to DOM element, you can simply treat
jQueryobject as array or use itsget()method like that:or
The above will return first object stored in the jQuery object – if there is only one, there should be no problems (if there are more, just change
0into other index to get appropriate element, or just omit the argument forget()to retrieve all the elements as array).Your code changed to use
jQueryYour code could look like this (if you insist on using hard-to-maintain event attributes):
except in this case using jQuery is completely useless and you can just operate directly on DOM elements, converting them to jQuery when needed 🙂
Your solution changed to bind events outside
<body>Your code using jQuery for binding events in jQuery 1.7+ could look like this:
See the above in action here: jsfiddle.net/tadeck/2PqPP/