I’m trying to wrap specific words (“Ethan”, “passionate”, “UX/UI”, and “Designer”) in a span class in a paragraph for individual styling. However, since “Ethan” is followed directly by a comma in the HTML, the JavaScript only selects it if I include the comma (“Ethan,”)—resulting in the comma being styled as well, which I don’t want. How can I apply the style only to “Ethan” without affecting the comma?
Here’s my current JS:
document.addEventListener('DOMContentLoaded', function() {
const herotext = document.getElementById('herotext');
const words = herotext.innerText.split(' ');
herotext.innerHTML = words.map(word => {
if (['Ethan', 'passionate', 'UX/UI', 'Designer'].includes(word))
{
return `<span style="color: #F33;">${word}</span>`;
} else {
return `<span>${word}</span>`;
}
});
});
And the HTML:
<h1 id="herotext">Hi, I’m Ethan, a passionate UX/UI Designer from the scenic landscapes of Northern Ireland.</h1>
Thanks!
I’ve already tried wrapping the word “Ethan” in a <span> element and applying a specific CSS style to it, but this didn’t work. The issue is that in the HTML, “Ethan,” appears as a single entity (with the comma directly after the name), preventing the span from targeting just “Ethan.”
Here’s the HTML I used:
<h1 id="herotext">Hi, I’m <span class="highlight">Ethan</span>, a passionate UX/UI Designer from the scenic landscapes of Northern Ireland.</h1>
And the CSS:
.highlight {
color: #333;
}
I know this is a very specific use case, but this is the only sentence I want to apply this algorithm to. Setting some rules around excluding commas from the styling seems like it would resolve the issue, I’m just not sure how to do this as I’m not a developer and have very very basic development knowledge – some help/a solution would be massively appreciated!