Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

265
Views
How just to get innertext, excluding child nodes

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

You can Use getElementsByTagName or use children property

document.getElementsByTagName('p')[0].getElementsByTagName("img");

document.getElementsByTagName('p')[0].children
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!