简体   繁体   中英

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM