I need to wrap each first letter of each word from line with specific css class "eachword" into "span" html tag - using the javascript. Meanwhile I have good worked script, except one issue, the script converts special characters like "&" into html format. So, here's what I have right now:
Before script is applied:
<a class="eachword" href="#">Models & Brands</a>
Script:
<script type="text/javascript">
window.onload = function()
{
var elements = document.getElementsByClassName("eachword");
for( var i=0; i<elements.length; i++)
{
elements[i].innerHTML = elements[i].innerHTML.replace(/\b([a-z])([a-z]+)?\b/gim, "<span class='firstletter'>$1</span>$2");
}
}
</script>
Result:
<a class="eachword" href="#"><span class="firstletter">Models &<span class="firstletter">a</span>mp; <span class="firstletter">Brands</span></a>
And I need this result:
<a class="eachword" href="#"><span class="firstletter">Models <span class="firstletter">& </span><span class="firstletter">Brands</span></a>
In "head" tag, I also have jQuery 1.7.2 included.
So, the question is, what's wrong with the code, where did I make mistake? Thanks for attention, hope for your help!
In vanilla JS, a bit faster I think:
var a = document.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
var words = a[i].innerHTML.split(" ");
for (j = 0; j < words.length; j++) {
if(words[j][0] != "&") {
words[j] = "<span class='firstletter'>" + words[j][0] + "</span>" + words[j].substring(1);
}
}
a[i].innerHTML=words.join(" ");
}
The more modern way:
var anchors = Array.from(document.getElementsByTagName("a"));
anchors.forEach(a => {
a.innerHTML =
a.textContent
.split(' ')
.map(word => {
if (word[0] != '&') {
return `<span class="firstletter">${word[0]}</span>${word.substring(1)}`;
} else {
return word;
}
})
.join(' ');
});
JSFiddle .
This seems to work for me, may be a bit clumsy though
$(document).ready(function()
{
// For each of the eachword class
$("a.eachword").each(function()
{
// Get the string (html) and split it by " " (like PHP's explode)
var self = $(this);
var theText = self.html();
var theTextArray = theText.split(" ");
// Cycle them
for (var i = 0; i < theTextArray.length; i++)
{
// Get this particular word and split it into individual letters
var thisWord = theTextArray[i];
var thisWordArray = thisWord.split("");
// Wrap the first letter if it is not a HTML char code
if (thisWordArray[0] != "&")
{
thisWordArray[0] = "<span class='firstletter'>"+thisWordArray[0]+"</span>";
}
// Stitch the letters back up
theTextArray[i] = thisWordArray.join("");
}
// Join the original string back up
var result = theTextArray.join(" ");
self.html( result );
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.