I’m trying to have plain (no jQuery, mootools, etc) JavaScript add span tags with numbered ID’s to each word within a certain class.
For example:
<p class="read-aloud">
Here's a test.
</p>
would become
<p class="read-aloud">
<span id="word001">Here's</span> <span id="word002">a</span> <span id="word003">test.</span>
</p>`
Punctuation needs to be included, but not quotes.
I have this (which I’ve modified from another post):
function add-readAloud-uIDs(matchClass)
{
var elems = document.getElementsByTagName('*'),i;
for (i in elems)
{
if((" "+elems[i].className+" ").indexOf(" "+matchClass+" ") > -1)
{
elems[i].innerHTML.replace(/\b([A-Za-z][a-z]*?-?’?'?[a-z]*?\.?,?!?\??)([ | ”])("?)/g, '<span id="word">$1</span>$2$3');
}
}
}
window.onload = function ()
{
add-readAloud-uIDs("read-aloud");
}
Also at jsfiddle
I’m having trouble finding a way to increment the ID’s. How might I go about this?
Also, the reason I don’t want to use a js library is because this is going to be running on the iPad. Performance is important, as well as the flexibility to use whichever library for other purposes needed without conflict.
You can use a custom replace function like this:
Demonstration: http://jsfiddle.net/jfriend00/5v54f/
For the definition of a word, I chose any sequence of characters that does not include whitespace, but you can obviously tweak the regular expression to your liking.