Here is a potential solution you can try:
document.querySelectorAll('p').forEach(el => {
const prefix = el.innerText.substr(0, el.innerText.length - 1);
const suffix = el.innerText.substr(el.innerText.length - 1);
el.innerHTML = `${prefix}<span class="colored">${suffix}</span>`;
})
The code uses document.querySelectorAll
to target all the <p>
elements on the page. Then, it loops through each element using NodeList#forEach
. Each iteration extracts all characters except the last one and stores it as 'prefix', followed by extracting the last character and storing it as 'suffix'. The content of the element is then reconstructed using innerHTML
, wrapping the single character in a <span>
using a template string.
This code assumes that you have CSS styling similar to this example:
.colored {
color: red;
}
document.querySelectorAll('p').forEach(el => {
const prefix = el.innerText.substr(0, el.innerText.length - 1);
const suffix = el.innerText.substr(el.innerText.length - 1);
el.innerHTML = `${prefix}<span class="colored">${suffix}</span>`;
})
.colored {
color: red;
}
<section>
<h1>Name</h1>
<p>John</p>
<p>Jacques</p>
<p>Peter</p>
<p>Robert</p>
</section>