How to place blinking _ after TypeWriter effect in HTML/CSS/JavaScript

I am trying to output Hello World_ with the typewriter effect and leave the _ blinking. Currently, I’m using HTML and CSS to make the _ blink, and I am using Javascript to type out Hello World in the typewriter effect. At the moment my code prints out the _ then Hello World. I have been having trouble getting it to look like Hello World_ with the underscore blinking still. Thank you!

<div id = "HelloWorld">
  <h1 id = "demo">
    <span class = "blink_me">_</span>
  </h1>
</div>

<script>
  var i = 0;
  var txt = 'Hello World';
  var speed = 150;

  (function typeWriter() {
    if (i < txt.length) {
      document.getElementById("demo").innerHTML += txt.charAt(i);
      i++;
      setTimeout(typeWriter, speed);
    }
  })();
</script>


.blink_me {
  animation: blinker 1.5s linear infinite;
}
@keyframes blinker {
  50% {
    opacity: 0;
  }

Output

So as you can see my output is _Hello World, but I’m trying to get Hello World_ with the _ blinking still. Thank you!

Answer

I will give two solutions.

Method 1.

Use rule direction: rtl to #demo. This rule will reverse your elements by swapping them.

Just add it to your css:

#demo {
    display: inline-block;
    direction: rtl;
}

var i = 0;
var txt = "Hello World";
var speed = 150;

(function typeWriter() {
    if (i < txt.length) {
        document.getElementById("demo").innerHTML += txt.charAt(i);
        i++;
        setTimeout(typeWriter, speed);
    }
})();
#demo {
    display: inline-block;
    direction: rtl;
}

.blink_me {
    animation: blinker 1.5s linear infinite;
}

@keyframes blinker {
    50% {
        opacity: 0;
    }
}
<div id="HelloWorld">
    <h1 id="demo">
        <span class="blink_me">_</span>
    </h1>
</div>

Method 2.

Create an additional span tag for animated text, specifying any class or id. Like this:

<h1 id="demo">
    <span class="text_out"></span>
    <span class="blink_me">_</span>
</h1>

var i = 0;
var txt = "Hello World";
var speed = 150;

(function typeWriter() {
    if (i < txt.length) {
        document.getElementsByClassName("text_out")[0].innerHTML += txt.charAt(i);
        i++;
        setTimeout(typeWriter, speed);
    }
})();
.blink_me {
    animation: blinker 1.5s linear infinite;
}

@keyframes blinker {
    50% {
        opacity: 0;
    }
}
<div id="HelloWorld">
    <h1 id="demo">
        <span class="text_out"></span>
        <span class="blink_me">_</span>
    </h1>
</div>