Search code examples
javascriptinnerhtmlcreateelement

Javascript innerHTML


I am currently learning Javascript DOM and innerHTML and found some problems in understanding innerHTML.

Here are my codes: http://jsfiddle.net/hphchan/bfjx1w70/1/

I have learnt standard DOM method and innerHTML methods and it works fine, BUT I don't know why it is wrong to code the following:

// this method fails
var element2 = document.createElement('p'); 
element2.innerHTML = "hello <em>Herbert</em>";

// standard methods of innerHTML method I learnt from textbook, BUT it requires to type tags in HTML
var element3 = document.getElementById('el');
element3.innerHTML = "innerHTML: hello <em>Herbert</em>";

I want to ask why it does not work for the first method. What is the problem of doing in this way? In addition, what if I don't want to type anything (including tags) in HTML and want to use innerText to fulfil the same output as what the JSFiddle shows "hello Herbert"?


Solution

  • The main error is the innerText usage. For most purposes, I would stay away from that in general, as innerHTML works for both situations. (text and markup)

    Although I suppose innerText has it's charms if you want to display HTML code as it is rather than render it.

    So, because you have an HTML tag inside the string, it's not a normal text node. If you simply used 'hello Herbert' instead of 'hello Herbert' it would work.

    var element2 = document.getElementById('el'); 
    
    element2.innerText = "hello Herbert";
    <p id='el'></p>

    The other problem is though you have the element, until you have actually put it in the DOM, it is useless, which is why example 2 isn't working.

    Try

    document.body.appendChild(element2);
    

    So,

    var element2 = document.createElement('p'); 
    
    element2.innerHTML = "hello <em>Herbert</em>";
    
    document.body.appendChild(element2);

    Hope it helps! Look at http://www.w3schools.com/jsref/met_node_appendchild.asp for more info.