views:

289

answers:

4

Hi,

I am trying to create a new Element in my javascript code and append it to one of my elements. But it seems that old IE browsers do not support this function and my code breaks on the line where I use appendChild function.

var child = document.createElement('span');
child.innerHTML = "Hello World!"; // Crashes here
parent.appendChild(child); // And here

Is there any alternatives I can use for IE?

Thank you.

P.S the code works fine in modern browsers.

UPD: The following code solves last part of my problem, I can append empty child to a parent:

var child = document.createElement('span');
if (parent.insertAdjacentElement){
   parent.insertAdjacentElement('beforeEnd', child);
}
else if (parent.appendChild) {
   parent.appendChild(child);
}

But I still need to put some data inside of child element. createTextNode, innerHTML, setAttributes do not work.

+1  A: 

Looks to me like it's crashing on the 2nd line. innerHTML is written with a lower-case i, not upper case. It could even be your first line as there's a typo, but I assume that's just in the question.

Jani Hartikainen
sorry, it's just a typo in the question.
negative
+1  A: 

This might be unrelated, but check this link for how someone else has solved this issue

Edit: and this link too

pǝlɐɥʞ
thanx, insertAdjacentElement solved the second problem, but I still can't modify newly created element. Neither innerHTML nor setAttribute functions work.
negative
What version of IE does innerHTML fail on? because AFAIK, IE5.5 fails when using innerHTML on <Select> elements, but here it looks like your using a <span>, just can't think of anything that should cause it to fail here...
pǝlɐɥʞ
A: 

Does this fix the problem?

var child = document.createElement('span');
child.appendChild(document.createTextNode("Hello World!"));
parent.appendChild(child);
Eli Grey
No, it doesn't like createTextNode() function.
negative
A: 

parent.innerHTML seems to work fine.

negative