Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

271
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda