Is it possible to wrap each word individually in a tag? On the example of the text: Cras ultricies ligula sed magna dictum porta just would have each word be individually in the tag

 var container = document.querySelector(".symbols"); var str = container.innerHTML; for(var i = 0; i < str.length; i++) { var e = document.createElement("span"); e.innerHTML = str[i]; container.appendChild(e); } 
  <div class="symbols">lorem ipsum sit ammet dolar </div> 

So I tried - it turns out to wrap only the sentence

  • 2
    definitely possible. - Grundy
  • for example, you break a line into words and wrap each one, another option is a replacement with a regular schedule - Grundy
  • it turns out to wrap only a sentence - I do not understand what the sentence is, if each character is wrapped here - Grundy

3 answers 3

The code you give can be converted to this:

 var container = document.querySelector(".symbols"); var arr = container.innerHTML.split(/\s+/); var str = ''; for(var i = 0; i < arr.length; i++) { if(arr[i]){ arr[i] = '<span>'+arr[i]+'</span>'; } } container.innerHTML = arr.join(' '); 
  <div class="symbols">lorem ipsum sit ammet dolar </div> 

Here, multiple spaces are taken into account, but not transferred to the final version (replaced by one space).

    For example, you can (ES6):

     str.split(' ').map(s => `<div>${s}</div>`).join(' ') 

    Or, if it is not possible to use template lines and arrow functions:

     str.split(' ').map(function (s) { return '<div>' + s + '</div>'; }).join(' '); 

    Generally speaking, the exact implementation depends on the context.

    • if several spaces in a row add an extra wrapper :-) - Grundy
    • in my example, too, if there is a space, it is also defined as a span - which is just superfluous - user33274
    • Well, if several in a row, then yes, the idea is to sort it out differently in real life) - Serafim Prozorov

    The problem of the code in question is that the loop goes by the characters of the line, not by words, so each character is wrapped.

    To correct you need to go by the words.

    Or, alternatively, use the replace method with a regular expression

     var container = document.querySelector(".symbols"); var str = container.innerHTML; container.innerHTML = str.replace(/\b[^\s]+?\b/g, $0 => `<span>${$0}</span>`); 
     span { border: 1px solid green; } 
     <div class="symbols">Cras ultricies ligula sed magna dictum porta</div> 

    • Grundy you are a masterpiece, I’m getting high on you both, why can't I choose two options Best? - user33274
    • will incorrectly handle non-alphabetic characters, for example. slash or hyphen - Sergiks
    • @Sergiks, yeah, thinks they are the boundary of the word - Grundy