Nick
Nick

Reputation: 2559

IE Javascript Error: Unable to get property '0' of undefined or null reference

I've narrowed my error down to the code below. For the sake of the example I'm appending text into the first div within a fragment. This seems to work on all browsers but IE doesn't seem to like it.

It looks like the issue is specifically the [0] index? Though I could be wrong.

<div id="hello"></div>

var frag = document.createDocumentFragment(),
        div = document.createElement('div');

    frag.appendChild(div);
    frag.children[0].innerHTML = "Hello";

    document.getElementById('hello').append(div);

Fiddle: https://jsfiddle.net/d758ma27/

The expected output is #hello would now contain the text "Hello" - Which it does, just not in IE. Any help would be great, this has well and truly confused me!

Currently testing on IE10 and below.

Upvotes: 2

Views: 4416

Answers (1)

GOTO 0
GOTO 0

Reputation: 47961

This is how I'd fix it.

var frag = document.createDocumentFragment(),
        div = document.createElement('div');
    
frag.appendChild(div);
frag.childNodes[0].innerHTML = "Hello";

document.getElementById('hello').appendChild(div);
<div id="hello"></div>

Note that I'm using childNodes rather than children to access the elements in the document fragment, and appendChild rather than append to add the new div element to the DOM in the document.

Upvotes: 4

Related Questions