I have a task where I need to identify the last word in a class and then enclose it with a span element so that I can style it using JavaScript.
<h1 class="title>A long tile</h1>
<h2 class="title>A long tile</h2>
should be transformed into
<h1 class="title>A long <span class="last-word">tile</span></h1>
<h2 class="title>A long <span class="last-word">tile</span></h2>
I found some jQuery solutions on Stack Overflow that were helpful, but I prefer a pure Javascript version.
I managed to make it work for the first element on the page with this code...
var paras = document.querySelector('.title');
function wrapLastWord(elem) {
const textContent = elem.textContent.split(" ");
const lastWord = textContent.pop();
const updatedContent = textContent.join(" ") + (textContent.length > 0 ? ` <span class='last-word'>${lastWord}</span>` : lastWord);
elem.innerHTML = updatedContent;
}
wrapLastWord(paras)
However, my goal is to target all elements with the .title
class, so I attempted to use querySelectorAll
and forEach
, but it's not working as expected.
var paras = document.querySelectorAll('.title');
paras.forEach(function wrapLastWord(elem) {
const textContent = elem.textContent.split(" ");
const lastWord = textContent.pop();
const updatedContent = textContent.join(" ") + (textContent.length > 0 ? ` <span class='last-word'>${lastWord}</span>` : lastWord);
elem.innerHTML = updatedContent;
}
wrapLastWord(paras)
})
I would appreciate any guidance or suggestions for making this work correctly or considering a different approach.