0

JS: how to get all elements created through JS

Var x = 0; btn.onclick = function (){ for(x = 0; x < 1; x++){ Var elm = doc...createElement("li"); aButton.onclick = function(){ elm.style.color = "#000" } } I need all the elms, so I can use them anywhere.

27th Oct 2019, 5:33 AM
Ginfio
Ginfio - avatar
9 Answers
+ 1
Ipang here,s the code i was working on. In the pickBtn.onclick = function(){ } I tried to use the class name, didn't work for me. https://code.sololearn.com/WphlX5xuimCR/?ref=app
27th Oct 2019, 5:23 PM
Ginfio
Ginfio - avatar
+ 1
Yes I can see that. So you want to collect all <li> elements after you create and add them to the <parent> right? you should finish adding all the necessary <li> first, then you can collect them by `document.querySelectorAll()` But in your code you try to collect BEFORE the new <li> element is appended to <parent>.
27th Oct 2019, 6:56 PM
Ipang
+ 1
Ginfio This code adds new elements on page load, then with a button we can collect the new elements by specifying the class in the call to `document.querySelectorAll()` https://code.sololearn.com/WdK7PQOle66T/?ref=app
27th Oct 2019, 7:18 PM
Ipang
+ 1
Ipang , I switched my code a little bit to make it look like yours. had the same problem. Do you think my code is fixable to collect all the created elements and give them positiom:absolute like o'm trying to do in the pickBtn.onclick ... function? How
27th Oct 2019, 10:12 PM
Ginfio
Ginfio - avatar
+ 1
Never mind. I got it figured out. I used for () ThankYou for your help. Ipang
27th Oct 2019, 11:08 PM
Ginfio
Ginfio - avatar
0
Maybe you can assign a class for the elements while you are creating/adding the elements, later on you can use `document.getElementsByClassName()` or `document.querySelectorAll()` to collect them. Please remove 'document.create("div")' from tags, no code (unless really necessary) should be in tags 👍
27th Oct 2019, 9:34 AM
Ipang
0
Ginfio h = document.querySelectorAll(".new_elm"); It seems you are trying to collect all elements having class 'new_elm' while in fact the newly created <list> element had not been added to the container <parent>. And what's this loop in the function `add` for anyway, going from 0 to 1 you pretty much only do one iteration. for (i = 0; i < 1; i++) { // codes here }
27th Oct 2019, 6:39 PM
Ipang
0
Ipang , the add function adds the new list in the parent. creates new elm.
27th Oct 2019, 6:48 PM
Ginfio
Ginfio - avatar
0
Ginfio Share the latest update of the code please? I'd like to see it too, so I can also learn from the problem, and what you did to overcome it 👍
28th Oct 2019, 4:09 AM
Ipang