Using jQuery With Custom XHTML Attributes And Namespaces To Store Data

I was talking to Brian Swartzfager yesterday about his new jQuery plugin for editable tables when I started to think about various ways to store meta-data in an XHTML document. I only recently learned about the jQuery data() method, which totally blew my mind! The data() method allows you to store arbitrary data with an XHTML DOM element. But then, I got to thinking about custom attributes. In XHTML, you can use namespaces to add custom attributes to your XHTML DOM elements.

I thought maybe custom attributes would be another way to store custom data. I know that namespaces do cause some problems in jQuery when you are searching for DOM elements; but, as far as setting and getting them, I figured that would be worth an experiment. In the following demo, I am creating IMDB link elements based on existing custom attributes:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:bn="www.bennadel.com"> <head> <title>Using jQuery With Custom XHTML Attributes</title> <script type="text/javascript" src="jquery-1.2.6.min.js"></script> <script type="text/javascript"> $( function(){ var jLI = $( "li" ); // Loop over each list istem to set up link. jLI.each( function( intI ){ var jThis = $( this ); var jLink = $( "<a></a>" ); // Set the link text (trim text first). jLink.text( jThis.text().replace( new RegExp( "^\\s+|\\s+$", "g" ), "" ) ); // Set the link href based on the IMDB // attribute of the list item. jLink.attr( { "href": jThis.attr( "bn:imdb" ), "bn:rel": "Pretty Cool Ladies" } ); // Replace the LI content with the link. jThis .empty() .append( jLink ) ; } ); } ); </script> </head> <body> <h1> Pretty Cool Ladies </h1> <ul> <li bn:imdb="http://www.imdb.com/name/nm0004742/"> Maria Bellow </li> <li bn:imdb="http://www.imdb.com/name/nm0184965/"> Christina Cox </li> <li bn:imdb="http://www.imdb.com/name/nm0226459/"> Ani DiFranco </li> </ul> </body> </html>

As you can see, the HREF attribute of the new link is based on the bn:imdb custom attribute of each list item. I am then setting a custom REL attribute (bn:rel) based on the type of node we are looking at. When we run the above code, we can see in FireBug that the XHTML was properly updated:

I tested this in FireFox, IE7, and Safari and all work fine. I doubt I would ever go this way instead of just using the data() method; but, it's interesting as an alternate approach for simple values. What's nice about it too is that the custom attributes can be built directly into the XHTML by ColdFusion before jQuery even has a chance to execute. This does give it an advantage over the data() method in specific use cases.

Tweet This Interesting post by @BenNadel - Using jQuery With Custom XHTML Attributes And Namespaces To Store Data Woot woot — you rock the party that rocks the body!



