Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

272
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda