innerHtml prepend text instead of appending

vlad picture vlad · Mar 7, 2014 · Viewed 7.5k times · Source

I have a function that emulates typing with few lines of basic JavaScript code, however it appends text, but I want to prepend text to the element before any other already existing text/elements without changing html structure.

How this can be achieved with simplest javascript possible?

JavaScript

var el = getElementById('one'), str = 'Abcdefg...'
function type(){
    el.innerHTML += str.charAt(i); i++;
    if(i < str.length){var t = setTimeout(type, 30);}
};type();

HTML

<span id="one">...<span id="endingEl"></span></span>

Answer

cookie monster picture cookie monster · Mar 7, 2014

Use .insertAdjacentHTML instead of .innerHTML.

el.insertAdjacentHTML("afterbegin", str.charAt(i));

The four positions available are:

  • "beforebegin" (directly before the current node)

  • "afterbegin" (inside the current node, at the beginning)

  • "beforeend" (inside the current node, at the end)

  • "afterend" (directly after the current node)


Avoid using .innerHTML += "..." type of solutions at all cost. It's an awfully destructive and expensive approach.