Gallex Gallex - 4 months ago 10
Javascript Question

How to wrap the first word of a title with a span

I would like to achieve something similar, but to wrap first word of every

<h1>
tag with a
<span>
tags. It should look like this:

<h1><span>This</span> is a title</h1>


I quess it's doneable without a plugin...

Answer

Use JavaScript String#repalce method

var tag = document.querySelector('h1');

tag.innerHTML = tag.innerHTML.replace(/^\s*\w+/, '<span style="color:red">$&</span>');
<h1>This is a title </h1>


FYI : Since it recreates the inner elements it will destroy any handler attached to its descendant element.


UPDATE : In case you want to update all h1 tag then you need to get all h1 and iterate over them.

Array.from(document.querySelectorAll('h1')).forEach(function(ele) {
  ele.innerHTML = ele.innerHTML.replace(/^\s*\w+/, '<span style="color:red">$&</span>');
});
<h1>This is a title </h1>
<h1>This is a title </h1>
<h1>This is a title </h1>
<h1>This is a title </h1>
<h1>This is a title </h1>