01 Aug 2010

JQuery and Element Objects

Part of the switch I'm making includes prototypejs to JQuery. No, not like I've found anything lacking in prototype. It's just about the change.
The transition has been quite easy very much unlike MySQL to MongoDB. The two javascript frameworks even share some methods that are exactly the same - same name, same work. The little problem however is the way both handles objects.
JQuery doesn't seem to work with core element objects. I will explain. Take a look at the sample code:

1
<p onclick="alert(this)">Sup?</p>

This will output something like object HTMLParagraphElement. This is what I'm referring to as the core element object. And you can't use this directly in JQuery. This won't work:

1
<p onclick="this.addClass('on')">Sup?</p>

It will in prototype though:

1
<p onclick="this.addClassName('on')">Sup?</p>

Thing is, it is necessary to convert any element object to JQuery's object with $(). So this will work:

1
<p onclick="$(this).addClass('on')">Sup?</p>

The knowledge of this simple thing, can save a lot of headache.

 

Looking for a simple marketing automation tool to automate your customer onboarding, retention and lifecycle emails? Check out Engage and signup for free.

 

My name is Opeyemi Obembe. I build things for web and mobile and write about my experiments. Follow me on Twitter—@kehers.

 

Next post: MongoDb - my first impressions