在下面的代码中,为什么document.querySelector()返回null?
var element = document.createElement('div');
element.classList.add('abc');
var test = document.querySelector("." + element.className);
答案 0 :(得分:2)
您需要添加.
var test = document.querySelector("."+element.className);
修改
您还需要将其添加到正文
document.body.appendChild(element);
答案 1 :(得分:2)
document.querySelector("."+element.className)
window.onload=function() { // body exists
var element = document.createElement('div');
element.classList.add('abc');
var test = document.querySelector("."+element.className);
console.log(test,element.className);
document.body.appendChild(element); // NOW the DIV exists in DOM
test = document.querySelector("."+element.className);
console.log(test);
}