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

234
Visualizações
How to target a div using content inside the div

I have 2 divs with same class name but different strings inside the div. I want to use an insertAfter the first div to display some additional text, but the text is being displayed under both divs:

<div class='test'>First Div</div>
<div class='test'>Second Div</div>

My approach:


if ( document.getElementsByClassName('test')[0] 
  && document.getElementsByClassName('test')[0].innerHTML == 'First Div'
   ) {
     $('<h2>Inserting New Text</h2>').insertAfter('.test')[0];
   }

But this adds the text after both the First Div and the Second Div. I want to know if there is a way to insert only once or insert after matching the string

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

No need for jQuery here. Use insertAdjacentHTML to add the new element.

// Pick up the first element with the test class
const el = document.querySelector('.test');

// Use `insertAdjacentHTML` to add the new div after it
el.insertAdjacentHTML('afterend', '<div>new text</div>');
<div class="test">First Div</div>
<div class="test">Second Div</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Just keep it simple, find all elements with target class and pick the first one:

const el = document.getElementsByClassName('test')
$('<div>new text</div>').insertAfter(el[0])
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='test'>First Div</div>
<div class='test'>Second Div</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

You can ask javascript to find the elements of the class and then convert the result into an array and find the first element that matches your condition.

const elements = Array.from(document.getElementsByClassName("test"));

const target = elements.find(el => el.innerHTML === 'First Div');

$('<h2>Inserting New Text</h2>').insertAfter(target);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='test'>First Div</div>
<div class='test'>Second Div</div>

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