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

216
Visualizações
JS Queryselector for dynamically created elements with attributes

Can i use query selector to find dynamically created elements that have an attribute?

I want to find the first element with val, but this won't find them. (divs with the values a-d are there just to show this works with "normally" created elements.)

let i = 4, wrapper = document.getElementsByClassName("wrapper")[0];
while (i-- > 0) {
    let div = document.createElement("div");
    div.val = i;
    wrapper.appendChild(div);
}

let myDiv = document.querySelector(".wrapper div[val]");
console.log("myDiv", myDiv);
<div class="wrapper">
</div>

<div class="wrapper">
    <div val="a"></div>
    <div val="b"></div>
    <div val="c"></div>
    <div val="d"></div>
</div>

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

0

Use Element.setAttribute() to set the attributes so they can be found by the querySelector:

let wrapper = document.getElementsByClassName('wrapper')[0]
let i = 4
while (i--) {
  let div = document.createElement('div')
  div.setAttribute('val', i)
  wrapper.appendChild(div)
}
let myDiv = document.querySelector('.wrapper div[val]')
console.log('myDiv', myDiv)
<div class="wrapper"></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