title: How to create a clickable span between the text in a div with Javascript
body: <p>There is an existing html div with text inside. I wish to modify the contents of the div with additional text, but with a span of text (B) in between the existing text (A) and what I am inserting (C). The span also has a css style implemented by id, but removed from code snippet as it does not directly matter.</p>
  
  <p>If the span was to be at the very end, I could simply append the span as a child, which would put it at the end of the div text. However any text I later add to the div will still come before the span. The span will always be at the end, at least as far as I know.</p>
  
  <p>Let us say existing div says "Hello World. " I wish to use Javascript to add the following:</p>
  
  <pre><code>var targetDiv = div;
  div.textContent = 'Hello World! ';
  var spanText = div.appendChild(document.createElement('span'));
  spanText.innerHTML = 'Click Me!';
  spanText.onclick = function(){
    perform task here;
  };
  div.textContent += ' Did you click it?';
  </code></pre>
  
  <p>The div would not show "Hello World. Click Me! Did you click it?" It would show "Hello World.  Did you click it?Click Me!"</p>
  
  <p>I've tried making the span inside the div using innerHTML when appending the text, such that it is like below:</p>
  
  <pre><code>var targetDiv = div;
  div.textContent = 'Hello World! ';
  targetDiv.innerHTML += '&lt;span&gt;Click Me!&lt;/span&gt; Did you click it?';
  var spanText = div.span; //and variations such as div.children(1);
  spanText.onclick = function(){
    perform task here;
  };
  </code></pre>
  
  <p>The problem here is that I'm guessing since it is in innerHTML, javascript does not recognize/find the span, so it cannot be assigned a variable name. Or assign onclicks and stuff onto it. Here, the text does display correctly, as "Hello World. Click Me! Did you click it?", but the onclick does not work. So I tried putting the onclick function (yes, a one-liner) inside the innerHTML as below:</p>
  
  <pre><code>var targetDiv = div;
  div.textContent = 'Hello World! ';
  targetDiv.innerHTML += '&lt;span onclick = "perform task here;"&gt;Click Me!&lt;/span&gt; Did you click it?';
  </code></pre>
  
  <p>This did not work either. Unlike the first and similar to the second attempt, text displays correctly but function does not work.</p>
  
  <p>As for why I'm doing such a pointless exercise, this is simply an abstracted example of what I'm working on, and I felt that uploading the actual code in this case would only bog it down with needless context. However I am ready to provide any clarification if any is needed.</p>
  
  <p>Vanilla JS please. I don't have JQuery on my project at the moment and putting it in for such a minor piece of code seems like overkill. </p>
  
  <p>Assistance would be much appreciated, thanks!</p>