Ianardo Ianardo - 1 month ago 13
Javascript Question

Split large block of text into individual spans with individual ids

PLEASE DO NOT MARK THIS AS DUPLICATE! THIS IS THE ONLY PURE JAVASCRIPT APPROACH WITH INDIVIDUAL ID'S

How do I split a large block of text into individual spans with id's that go like this:

<span class="word" id="word0">Breaking </span>
<span class="word" id="word1">News. </span>
<span class="word" id="word2">Spring </span>
<span class="word" id="word3">is </span>
<span class="word" id="word4">here </span>
<span class="word" id="word5">to </span>
<span class="word" id="word6">stay. </span>


If the input was "Breaking News. Spring is here to stay."

I want to get the input from a specific div and output it into the same div. Please do not use jquery for this.

Thanks!

Answer

var s = "Breaking News. Spring is here to stay.";
    var arry = s.split(" ");   // This will split on all single whitespaces
    var arry = s.split(/\s+/); // This will split on any group of whitespaces
    
    var output = "";

    var len = arry.length;
    for(var i = 0; i < len; ++i){
       output += "<span id='word" + i + "'>" + arry[i] + "</span>" ;
    }

    alert(output);

    // Or, to be more core DOM compliant
    var d = document.createElement("div");

    for(var i = 0; i < len; ++i){
      var sp = document.createElement("span");
      sp.setAttribute("id", "word" + i);
      sp.textContent = arry[i];
      d.appendChild(sp);
    }

    alert(d.innerHTML);

Comments