I am converting the following jQuery code to vanilla JavaScript and have become stuck on the final bit.
You will see in my snippet with the vanilla JS code, the span wrapped word is being inserted before the first word instead of replacing it.
Am I incorrectly using the insertAdjacentHTML
function?
jQuery
var node = $(".content h1").contents().filter(function () { return this.nodeType == 3 }).first(), text = node.text(), first = text.slice(0, text.indexOf(" ")); if(!node.length) return; node[0].nodeValue = text.slice(first.length); node.before('<span>' + first + '</span>');
const splitHeadings = (() => { let node = document.querySelector(".content h1"); if (node) { let content = node.textContent.trim(); let first = content.slice(0, content.indexOf(" ")); node.childNodes[0] = content.slice(first.length); console.log(first); console.log(content); first = `<span>${first}</span>`; node.insertAdjacentHTML("afterbegin", first); } })();
h1 span { color: red; }
<div class="content"> <h1>Sample string with multiple words</h1> </div>
Advertisement
Answer
How about not inserting but just replacing
Using map
const splitHeadings = (() => { let node = document.querySelector(".content h1"); if (node) { let content = node.textContent .trim() .split(" ") .map((word,i) => i===0 ? `<span>${word}</span>` : word); node.innerHTML = content.join(" ") } })();
h1 span { color: red; }
<div class="content"> <h1>Sample string with multiple words</h1> </div>
Using regex
const splitHeadings = (() => { let node = document.querySelector(".content h1"); if (node) { let content = node.textContent .trim() .replace(/w+/,match => `<span>${match}</span>`); node.innerHTML = content; } })();
h1 span { color: red; }
<div class="content"> <h1>Sample string with multiple words</h1> </div>