A long time ago (see: 2005), I released a tutorial covering this same subject. However, I decided it's time to completely revise the tutorial and actually correct the numerous mistakes I had on this function. So, here we go...
To begin with, document.createAttribute() is similar to the DOM functions of document.createElement(), document.createDocumentFragment(), and document.createComment(). It creates an "attribute" node as opposed to an element node (createElement), a document fragment (createDocumentFragment), or a comment node (createComment) however. Seeing a pattern yet? I see one.
I will not discuss what an attribute node is since it is fairly straight forward if I just show this example: <td attribute="value_of_attribute">cell content</td>
A quick thing to mention is that the nodeType of an attribute node is 2. The most amazing part is that both IE and Fx recognize this. IE conforming to standards? Amazing, I know.
Anyways, back to the task at hand. document.createAttribute() is most commonly used as an alternative to element.setAttribute("name", "value"); It's a bit longer, but is more of a true DOM method. I'll now show you an example of usage and then break it down for you. (Also, Code 1 and Code 2 are essentially equivalent.)
BREAK IT DOWN... no seriously, I'm going to break this code down for you guys.
var newAttr = document.createAttribute("attrname"); Well, this line is straight forward mostly. We're creating a new attribute node and assigning it to a variable for reference.
newAttr.nodeValue = "new_value"; Now that we've created the attribute, it kinda needs a value. We alter this using the nodeValue property. Assign it to whatever you want the new value to be.
element.setAttributeNode(newAttr); And here we finally set the attribute node into the actual element. If we were to use getAttribute("attrname") on this element now, we'd find the value of "new_value" that we just recently assigned to it.
That's really all there is to document.createAttribute(). Honestly, I'd recommend using the alternative setAttribute() method, but this one can work just as well (besides taking up a bit more script room.)
Thanks for this tutorial. Very well written. I would agree with you about just using setAttribute() except the reason I came looking for a tutorial like this in the first place is because I was getting a script error of "element.setAttribute() is not defined" when trying to use setAttribute on an element that doesn't already contain the kind of attribute that I was looking to add so I had to wrap my attribute creation in a Try Catch, using setAttribute() in the Try and your createAttribute technique in my Catch.