I want to be able to add custom tags around just text, so say I have:
<p>Some text <img src="" /> more text </p>
How can I get my custom tags around 'Some text' and 'more text' ? The conditions will be dynamic so I can't hard code for any one instance. Need to do child nodes too, not sure if the img in this example is considered a child or not.
If you scan for childNodes you can check each node type to see if it is a Text element. If so, replace that entry in the parent with a version that is wrapped in your tag. Here I've chosen <strong> to bold the text and show the effect after replacement.
const trigger = document.getElementById("trigger");
trigger.addEventListener("click", () => {
const parent = document.querySelector("p");
const customTag = "strong";
for (const childNode of parent.childNodes) {
if (childNode instanceof Text) {
const text = childNode.data;
const customElement = document.createElement(customTag);
customElement.innerText = text;
parent.replaceChild(customElement, childNode);
}
}
});
<p>Some text <img src="https://www.gravatar.com/avatar/dc3dc4d5e0f2ded6a626771d2f1ae2a6?s=64&d=identicon&r=PG&f=1" /> more text </p>
<button id="trigger">Wrap text with tag</button>
You can Use getElementsByTagName or use children property
document.getElementsByTagName('p')[0].getElementsByTagName("img");
document.getElementsByTagName('p')[0].children