KOMPX.COM or COMPMISCELLANEA.COM   

Wrap each word of text in <span> tag (JavaScript)

Wrapping each word of text content of an element in span tag in JavaScript:

Wrapping each word of text in SPAN tag
Wrapping each word of text in SPAN tag

HTML code:


<div class="example">
	Wrapping each word of text in SPAN tag
</div>

JavaScript code:


<script>
var text = document.querySelector('.example').textContent;
var text_wrapped = text.replace(/\w+/g, '<span>$&</span>');

// Printing the result
document.querySelector('.example').innerHTML = text_wrapped;
</script>

CSS code:


/* Styling the look */
.example span:nth-of-type(odd){color: #c00;}
.example span:nth-of-type(even){color: #009;}

Links

  1. String.prototype.replace(): developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
  2. Regular expression syntax cheat sheet: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Cheatsheet
  3. How to wrap each word of an element in a span tag?: stackoverflow.com/questions/8609170/how-to-wrap-each-word-of-an-element-in-a-span-tag
Browser support
Windows
Internet Explorer 9.0+
Edge 12.0+
Firefox 3.5+
Google Chrome 1.0+
Opera 10.0+
Safari 3.1+
Linux
Firefox 3.5+
Google Chrome / Chromium
Opera 10.0+
iOS
Safari 2.0+
Android
Samsung Internet 1.0+
Chrome 18.0+
Firefox 4.0+
Opera 10.1+
More