Thursday, April 14, 2011

document.getElementsByName bug in IE

Internet Explorer apparently has a bug in it that prevents you from using getElementsByName on document elements that have been created using document.createElement. This is a known issue with Internet Explorer and for some reason no one seems to have done anything to fix it (or is this the way it is meant to function?). The following (although perfectly legal code) does not seem to work on IE, although it works just fine on Firefox (and possibly other browsers although I haven't tested):



<html>
<head>
<script type="text/javascript">
function addTextBox()
{
var div = document.getElementById('addToDiv');
var tb = document.createElement('input');
tb.type = 'text';
tb.name = 'textbox';
tb.value = 'data';
div.appendChild(tb);
}

function countBox()
{
alert('Number of textboxes: ' + document.getElementsByName('textbox').length);
}
</script>
</head>
<body>
<input type="button" value="Add Input Box" onclick="addTextBox();" />
<input type="button" value="Count TextBoxes" onclick="countBox();" />
<div id="addToDiv">

</div>
</body>
</html>



A work around to this problem is using innerHTML as opposed to createElement in order to add a new element. This code seems to fix the problem and works fine on all browsers (I imagine):


<html>
<head>
<script type="text/javascript">
function addTextBox()
{
var div = document.getElementById('addToDiv');
var tb ="<span><input type='text' name='textbox' value='data' /></span>";

div.innerHTML = div.innerHTML + tb;
}

function countBox()
{
alert('Number of textboxes: ' + document.getElementsByName('textbox').length);
}
</script>
</head>
<body>
<input type="button" value="Add Input Box" onclick="addTextBox();" />
<input type="button" value="Count TextBoxes" onclick="countBox();" />
<div id="addToDiv">

</div>
</body>
</html>

No comments:

Post a Comment