Tuesday, August 26, 2008

jQuery Quick Tip: In general $(this).attr("attribute") = this.attribute

jQuery is a very useful JavaScript library for manipulating you web pages. However, I have seen it used to get attribute values when it doesn't have to be, normally to get element attributes. For example, opening all links with a class external and giving them a title (tooltip).

$("a.external").click( function()
  {
    window.open($(this).attr("href"));
    return false;
  }
).each( function()
  {
    $(this).attr("title", $(this).attr("title") + " External link: " + $(this).attr("href"));
  }
);

Would be the same as

$("a.external").click( function()
  {
    window.open(this.href);
    return false;
  }
).each( function()
  {
    this.title += " External link: " + this.href;
  }
);

There are some attributes that in JavaScript aren't the same as they are in html. The ones you may have issues with are listed below.

for          (htmlFor)
class        (className)
readonly     (readOnly)
maxlength    (maxLength)
cellspacing  (cellSpacing)

Doing this rather than using attr cuts down on code size and may improve performance.

2 comments:

Anonymous said...

this doesn't always work in some browsers and situations.. using the $ ensures it will cross browser compatible and save headaches later.

Sam said...

Which browsers does it have a problem with?