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

215
Views
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 answers
Answer question

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 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!