Inspecting jQuery internals and storing information

Neeraj Singh

Neeraj Singh

July 23, 2009

Following code has been tested with jQuery 1.3 .

Let's say that I have bound all the links to display an alert.

$("a").bind("click", function (e) {
  e.preventDefault();
  alert("clicked");
});

Mine is a large application and a co-worker has added another javascript file which does this

$("a").bind("click", function (e) {
  e.preventDefault();
  alert("hello");
});

Now if I click on a link I get two alerts. Not good. One way to debug would be to go through all the included javascript files.

However it would be cool if there is a way to find all the click handlers associated with an element.

jQuery has data method which it uses internally to store information. jQuery uses data method to store all the handlers associated with an element. We could use this information to our advantage. Here I am trying to find out all the click handlers associated with the first link.

var output = jQuery.data($("a").get(0), "events");

jQuery.each(output.click, function (key, value) {
  alert(value);
});

The output looks like this

function (e) { e.preventDefault(); alert("clicked"); }
function (e) { e.preventDefault(); alert("hello"); }

jQuery.data method is also very useful if you want to store some information about an element. For example, in an application you need to store information about people. In the html page you are only displaying names. And when a name is clicked then you want to display age, hometown and the company they work for. You can store information about each user using jQuery.data and you can retrieve it when username is clicked.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.