createElement and getElementsByName not working in IE?

M

mitch

It seems like if you create an element dynamically with createElement()
and then try to get it later with getElementsByName()
it's found in Firefox but not in IE. Here's an example program.

Is there something wrong with the program, or is there another way to
get elements that have been created dynamically? Thanks.

<html>
<body>

<SCRIPT>
function addCB(){
var s = document.getElementById("theSpan");

var cb = document.createElement("input");
cb.type = "checkbox";
cb.name = "theCheckbox";

s.appendChild(cb);

var names = document.getElementsByName("theCheckbox");

var nameStr = (names) ? names.length : "null";

alert("names=" + nameStr);

}

</SCRIPT>

<SPAN ID="theSpan" onClick = "addCB()" > click here </SPAN>

</body>
</html>
 
R

Richard Cornford

mitch said:
It seems like if you create an element dynamically with
createElement() and then try to get it later with
getElementsByName() it's found in Firefox but not in IE.

Yes, that is one of those IE bugs.

function addCB(){
var s = document.getElementById("theSpan");

var cb = document.createElement("input");
<snip>

At this point you have a reference to the element. Instead of throwing
this reference away you could hang on to it, and accumulative it with
references to the other like-named elements you create and then you
would not need to have the browser go searching for it later. I.E:-

Globally:-

var namedEls = {theCheckbox:[]};

- and upon creation:-

namedEls.theCheckbox[namedEls.theCheckbox.length] = cb;

- and then - namedEls.theCheckbox - will be an array of the elements you
create under the same name and may empoyed by any code that needs it.

Richard.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top