All fixed now. For future reference in case any one wants to do something similar. The reason why the code above was only changing every SECOND input field is because as each input node is replaced by the new span node, the nodeList is dynamically shrinking in size and thus our iterator "i" is no longer pointing to the input element we just replaced (because it is gone baby gone) and so is now pointing to the next input element in the node list. Thus, there is no need to increment "i" when looping through.
Below is my modified/final code. The function tagToSpan(tagName) now accepts an arguement as to what type of tag to look for and replace with spans. The function itself is being called from a function pageInit() which is called by the body onLoad event handler.
Code:
function tagToSpan(tagName) {
tagNodeList = document.getElementsByTagName(tagName);
for(i = 0; i < tagNodeList.length; i++) {
theInput = tagNodeList.item(i);
if (tagName == 'input' && theInput.type != 'text') {
// do nothing
}
else {
newSpan = document.createElement('span');
newSpan.innerHTML = theInput.value;
theInput.parentNode.replaceChild(newSpan, theInput);
i--;
}
}
}
function initPage() {
tagToSpan('input');
tagToSpan('select');
tagToSpan('textarea');
}
Bookmarks