vlad vlad - 10 months ago 78
HTML Question

innerHtml prepend text instead of appending

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?


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


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

Answer Source

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.