Skip to content

Instantly share code, notes, and snippets.

@Tatsh
Last active October 4, 2015 14:38
Show Gist options
  • Save Tatsh/2654474 to your computer and use it in GitHub Desktop.
Save Tatsh/2654474 to your computer and use it in GitHub Desktop.
Add labels based on data-label attribute , handle LTR/RTL
var addLabels = function (form) {
// Thanks to yorick
var collections = ['input', 'textarea', 'select'].map(form.getElementsByTagName.bind(form));
var labelText, labelEl;
var d = document, i, j, ilen;
var dir = (!form.dir ? (!d.dir ? 'ltr' : d.dir) : form.dir).toLowerCase();
var insertLabel = function (labelEl, inputEl) {
var ref = dir === 'ltr' ? inputEl : inputEl.nextSibling;
ref.insertBefore(labelEl, ref);
};
i = j = 0;
len = collections.length;
for (ilen = collections[i].length; i < len && j < ilen; i++, j++) {
labelText = collections[i][j].getAttribute('data-label');
if (labelText) {
labelEl = d.createElement('label');
labelEL.appendChild(d.creatTextNode(labelText));
if (collections[i][j].id) {
labelEL.htmlFor = collections[i][j].id;
}
insertLabel(labelEl, collections[i][j]);
}
/*for (i = 0; i < collections.length; i++) {
for (j = 0; j < collections[i].length; j++) {
labelText = collections[i][j].getAttribute('data-label');
if (labelText) {
labelEl = d.createElement('label');
labelEL.appendChild(d.creatTextNode(labelText));
if (collections[i][j].id) {
labelEL.htmlFor = collections[i][j].id;
}
insertLabel(labelEl, collections[i][j]);
}
}
}*/
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment