How to get elements inside tags using queryselector?

coder picture coder · Feb 28, 2017 · Viewed 22.4k times · Source
var divElement = document.createElement("div");
divElement.setAttribute('id', 'Items');

var ulElement = document.createElement("ul");
var liElement = document.createElement("li");
var spanElement1 = document.createElement("span");
var spanElement2 = document.createElement("span");
liElement.appendChild(spanElement1);
liElement.appendChild(spanElement2);
ulElement.appendChild(liElement);

when I enter selector query, I cant get elements.

document.querySelectorAll("divElement ul li"); should give
document.querySelectorAll("#Items ul li");

but its not working, how to get the id at runtime????

Answer

coder picture coder · Mar 1, 2017

finally came up with solution. we can get "id" from the user using getElementById and then its simple to apply query selector.

document.getElementById(id).querySelectorAll('ul li');