Search code examples
javascripthtmlfunctioninnerhtmlcharat

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?

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>

Solution

  • 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.