JavaScript:将内容附加为nextSibling的子项

时间:2014-04-10 09:21:07

标签: javascript html

我尝试追加到多个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。

3 个答案:

答案 0 :(得分:3)

querySelectorAll会返回元素的列表。该列表没有nextSibling属性,因此您的第二行会在undefined中为您提供next

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);
    }
}

答案 1 :(得分:2)

您的代码中存在多个逻辑错误。 @T.J. Crowder完美地描述了它们。

但是,在您的情况下,我宁愿在querySelectorAll中使用CSS下一个兄弟选择器:

var next = document.querySelectorAll("[data-color='blue'] + *");
for (var i = 0, len = next.length; i < len; i++) {
    var insertdiv = document.createElement('p');
    insertdiv.className   = 'content';
    insertdiv.textContent = 'My Content';
    next[i].appendChild(insertdiv);
}

DEMO: http://jsfiddle.net/8uywP/

答案 2 :(得分:1)

为什么不将它们添加到.yellow div中?像这样:

var yellow = document.getElementsByClassName("yellow");

for (var i=0, l = yellow.length; i<l; i++) {
    var insertdiv = document.createElement('p');
    insertdiv.className   = 'content';
    insertdiv.textContent = 'My Content';    

    yellow[i].appendChild(insertdiv);
}

<强> Working Fiddle example

没有必要&#34; Traverse&#34;如果你有一个关于你需要的元素的课程,那就像那样。