Jesper
Jesper

Reputation: 1096

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>

Upvotes: 0

Views: 1330

Answers (1)

aerial
aerial

Reputation: 1198

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>

Upvotes: 1

Related Questions