JavaScript:DOM 操作,然后搜索所有元素



我将几个新元素(通过AJAX(加载到DOM中。之后,我想"刷新"文档变量以选择现有元素和新元素。

我试图用这个小例子来简化我的问题:

// Creating a new element and insert it into DOM
var newdiv = document.createElement('div');
newdiv.style.color = 'red';
newdiv.innerHTML = 'this is a new div container';
newdiv.classList = 'newdiv';
document.getElementById('existingdiv').appendChild(newdiv);
// Search the complete DOM for the new element and try to select it (but abc is null)
var abc = document.querySelector('newdiv');
abc.style.color = 'blue';

有什么想法(没有jQuery(吗?

newdiv是一个类而不是一个元素。要达到目标,您必须在选择器中指定点(.(以及类名:

var abc = document.querySelector('.newdiv');
之后

,我想"刷新"文档变量以选择现有元素和新元素。

没必要,document活的

querySelector('newdiv')查找标记名称newdiv的元素。您可能的意思是querySelector('.newdiv'),它在 DOM 中查找具有该类的第一个元素。

现场示例:

// Creating a new element and insert it into DOM
var newdiv = document.createElement('div');
newdiv.style.color = 'red';
newdiv.innerHTML = 'this is a new div container';
newdiv.classList = 'newdiv';
document.getElementById('existingdiv').appendChild(newdiv);
// Search the complete DOM for the new element and try to select it (but abc is null)
var abc = document.querySelector('.newdiv');
abc.style.color = 'blue';
<div id="existingdiv"></div>

最新更新