Latest Tweets:
We all agree that although the DOM itself does a million tricks, it sometimes just lack the right attribute. When it comes to storing metadata, unorthodox means are often used, furthermore littering the DOM. Some may say that <element aCustomAttribute=”…”> is not workable, but today we’ll prove them wrong.
The secret recipe here is called Customized DTDs.
—
Sidebar: What is DTD?
DTD stands for Document Type Definition ( http://en.wikipedia.org/wiki/Document_Type_Definition ) and is a crucial part in defining what belongs, and what does not, to the DOM that refers it.
I’ll skip the technical part (a partial spec is on Wikipedia already, check if you’re free) and dive right into one implementation —
—
How to make use of custom attributes, and have them validate
First of all we need to write a custom .dtd file. But there are ways to make them inline (yikes!) — simply extend the !DOCTYPE:
<!DOCTYPE html PUBLIC ”-//W3C//DTD XHTML 1.0 Transitional//EN” ”http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd” [
<!ATTLIST textarea maxlength CDATA #IMPLIED>
<!ATTLIST textarea required (true|false) #IMPLIED>
<!ATTLIST input required (true|false) #IMPLIED>
<!ATTLIST select required (true|false) #IMPLIED>
]>
That works on a single page, on an ad-lib basis, but might not quite work if your site has a bunch of custom attributes used and reused. However, if you wish to use a customized DTD file across your site, the !DOCTYPE tag must be changed since the customized DTD might not have been registered publicly (so the PUBLIC keyword could not be used); W3C validation would also fail (for the page uses a non-standard DTD).
Ah, who cares. ;)
Remember to read http://www.alistapart.com/articles/customdtd .
—
Accessing custom attributes from jQuery
Just use $(element).attr(‘…’) — it takes pretty much anything.
—
BONUS: Building custom selectors for jQuery so we can say, say, $(“a:brisk”)
To make good use of JavaScript’s beautiful presentation power and make things like $(“element:customSelector”) work, one simply needs to look into jQuery.extend().
Check out Using jQuery.extend to extend jQuery itself also.
The code looks like:
jQuery.extend(jQuery.expr[“:”], {
text : “a.type==’text’”,
radio : “a.type==’radio’”,
checkbox : “a.type==’checkbox’”
});
But as always, it should not be surprising that we can also do
cool: “jQuery(a).attr(‘coolness’) >= 42”
and it will work!
—
Anecdote
Please please please at least try and use $(element).data — and please do not ask the DOM every time for the data. Try making the DOM only a representing component, and keep all the number crunching to yourself in code. Treat the DOM as a “view”, that is constantly updated to reflect the model, instead of the opposite (“We need that variable now, so let’s ask the DOM…”).
—
Origin: Evadne Wu 2010/02/12