PDA

View Full Version : Dom Helper Reserved Word Hack



ojintoad
17 Oct 2006, 10:39 AM
Jack rightly changed the attribute 'class' to cls in his dom helper to not interfere with reserved words. Today I was using it to create a form and when I got to the label tag attempted to assign the 'for' attribute. It didn't work since 'for' is a reserved word(for for loops), and the code to manipulate the reserved words in the Dom helper is privatized, so I couldn't overload it. The simple way to modify this without writing your own version of the code is to change the attribute after the element is generated.

Here's one way that uses regular expressions on the entire form's innerHTML.


var dh = YAHOO.ext.DomHelper;
dh.append('instantiatedForm1', {
tag: 'label', id: 'nameLabel', remove:"for=\'name\'", html: 'Name'
}
);
dh.append('instantiatedForm1', {
tag: 'input', id: 'name', type: 'text'
}
);
dh.append('instantiatedForm1', {
tag: 'label', id: 'ageLabel', remove:'for=\'age\'', html: 'Age'
}
);
dh.append('instantiatedForm1', {
tag: 'input', id: 'age', type: 'text'
}
);
var form = document.getElementById('instantiatedForm1');
form.innerHTML = form.innerHTML.replace(/remove="for='(\w+)'"/g, 'for=\"$1\"');


I liked this option since it required only one dom lookup and, I imagine, it could possibly be done on the entire Body element. I also like it since it keeps the code where it should be. The regular expression /remove="for='(\w+)'"/g looks for the remove tag that gets generated, captrues the words in the parens. The replace function uses the captured word. Individual elements can't be done this way since there's no way to access an element tag's own HTML.

The other option is to not specify the for element at all, then save the returned label element from the dom helper functions and use element.setAttribute('for', <formItemId>);.


var dh = YAHOO.ext.DomHelper;
var label = dh.append('instantiatedForm1', {
tag: 'label', id: 'nameLabel', html: 'Name'
}
);
label.setAttribute('for', 'name');


Either technique should work for any reserved word.

jack.slocum
17 Oct 2006, 10:56 AM
Did you try quoting the attribute like this:



var dh = YAHOO.ext.DomHelper;
var label = dh.append('instantiatedForm1', {
tag: 'label', id: 'nameLabel', 'for': 'name', html: 'Name'
}
);

ojintoad
17 Oct 2006, 11:05 AM
Egg on my face! I didn't see your response to my comment. Tried to be too helpful.

jack.slocum
17 Oct 2006, 12:22 PM
Being helpful is always a good thing! I'm sure other people will wonder the same thing and having a post about it will be good.