Why Is "Element.Innerhtml+=" Bad Code

Why is element.innerHTML+= bad code?

Every time innerHTML is set, the HTML has to be parsed, a DOM constructed, and inserted into the document. This takes time.

For example, if elm.innerHTML has thousands of divs, tables, lists, images, etc, then calling .innerHTML += ... is going to cause the parser to re-parse all that stuff over again. This could also break references to already constructed DOM elements and cause other chaos. In reality, all you want to do is append a single new element to the end.

It's better to just call appendChild:

var newElement = document.createElement('div');
newElement.innerHTML = '<div>Hello World!</div>';
elm.appendChild(newElement);​​​​​​​​​​​​​​​​

This way, the existing contents of elm are not parsed again.

NOTE: It's possible that [some] browsers are smart enough to optimize the += operator and not re-parse the existing contents. I have not researched this.

div.getelementbyid(id).innerHTML = giving out error

The problem is you need to pass the id of the element to document.getElementById(), but you are passing a dom element reference(Since movieNetwork is the id of the element that gets copied as a property of the window object) so even if you have not declared movieNetwork that is referring to a dom element reference.

In your case you need to pass a string literal like

document.getElementById('movieNetwork')

Or in html5 browsers you could just say

movieNetwork.innerHTML = "";

Js, document.getElementById(ID).innerHTML, error

document.getElementById(id) finds an element with a given id value in your HTML. An id value looks like this:

<div id="myHeader">Some Content</div>

And, then you can find that element with:

document.getElementById("myHeader");

ID values must be unique in each document so there should only ever be one element with a given ID.


If an id isn't what you really want, you can find elements other ways, by tag type, by class name, by attribute, etc... using CSS selectors with document.querySelectorAll().

For example, if you wanted to find all <h3> tags, you could do this:

var items = document.querySelectorAll("h3");

Here are some other reasons that document.getElementById(...) might fail to find what you want it to find:

  1. The Javascript code is running before the DOM elements have been parsed and loaded so thus the element is actually not there yet when you're running the code. This is common with code run from the <head> section of the document.

  2. You have an HTML error in how you are specifying the id value in the HTML.

  3. You have an HTML error that causes the browser not to parse your HTML properly.

  4. You have a script error that cause your script to abort before it gets to the part you want to run.

Cannot set property 'innerHTML' of null

You have to place the hello div before the script, so that it exists when the script is loaded.

Can scripts be inserted with innerHTML?

You have to use eval() to execute any script code that you've inserted as DOM text.

MooTools will do this for you automatically, and I'm sure jQuery would as well (depending on the version. jQuery version 1.6+ uses eval). This saves a lot of hassle of parsing out <script> tags and escaping your content, as well as a bunch of other "gotchas".

Generally if you're going to eval() it yourself, you want to create/send the script code without any HTML markup such as <script>, as these will not eval() properly.

Executing script elements inserted with .innerHTML

The OP's script doesn't work in IE 7. With help from SO, here's a script that does:

exec_body_scripts: function(body_el) {
// Finds and executes scripts in a newly added element's body.
// Needed since innerHTML does not run scripts.
//
// Argument body_el is an element in the dom.

function nodeName(elem, name) {
return elem.nodeName && elem.nodeName.toUpperCase() ===
name.toUpperCase();
};

function evalScript(elem) {
var data = (elem.text || elem.textContent || elem.innerHTML || "" ),
head = document.getElementsByTagName("head")[0] ||
document.documentElement,
script = document.createElement("script");

script.type = "text/javascript";
try {
// doesn't work on ie...
script.appendChild(document.createTextNode(data));
} catch(e) {
// IE has funky script nodes
script.text = data;
}

head.insertBefore(script, head.firstChild);
head.removeChild(script);
};

// main section of function
var scripts = [],
script,
children_nodes = body_el.childNodes,
child,
i;

for (i = 0; children_nodes[i]; i++) {
child = children_nodes[i];
if (nodeName(child, "script" ) &&
(!child.type || child.type.toLowerCase() === "text/javascript")) {
scripts.push(child);
}
}

for (i = 0; scripts[i]; i++) {
script = scripts[i];
if (script.parentNode) {script.parentNode.removeChild(script);}
evalScript(scripts[i]);
}
};

document.getElementById(demo).innerHTML = Math.ceil((Math.random()*10)-1); only prints 1 number?

Because you are replacing the innerHTML all the time, not adding something to it.

To add content, use += instead of just =: