我正在尝试附加到多个 div 的下一个元素。到目前为止我有这个:
HTML
<pre data-color="blue"></pre>
<div class="yellow></div>
<pre data-color="blue"></pre>
<div class="yellow></div>
<pre data-color="blue"></pre>
<div class="yellow></div>
函数运行后,内容应如下所示:
<pre data-color="blue"></pre>
<div class="yellow><p class="content">My content</p></div>
<pre data-color="blue"></pre>
<div class="yellow><p class="content">My content</p></div>
<pre data-color="blue"></pre>
<div class="yellow><p class="content">My content</p></div>
这是我迄今为止的功能:
var blue = document.querySelectorAll("[data-color='blue']");
var next = blue.nextSibling;
for (var i=blue.length; i--;) {
var insertdiv = document.createElement('p');
insertdiv.className = 'content';
insertdiv.textContent = 'My Content';
next[i].parentNode.appendChild(insertdiv, blue[i]);
}
但无法让它正常工作。
请不要使用 jQuery。
最佳答案
querySelectorAll
返回元素的列表。该列表没有 nextSibling
属性,因此第二行在 next
中为您提供 undefined
。
var blues, i, insertDiv;
blues = document.querySelectorAll("[data-color='blue']");
for (i = 0; i < blues.length; ++i) {
if (blues[i].nextSibling) {
console.log(blues[i].nextElementSibling.tagName);
insertDiv = document.createElement('p');
insertDiv.className = 'content';
insertDiv.textContent = 'My Content';
blues[i].nextElementSibling.appendChild(insertDiv);
}
}
关于JavaScript:将内容附加为 nextSibling 的子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22983838/