2016-02-22 123 views
1

我需要使用JS在HTML中的特定嵌套类中创建一个新元素。所以在这个例子中,我只需要在“collies”类嵌套在“dogs”中的时候创建一个“paw-print”类的新跨度。向嵌套类添加新元素

这是我到目前为止有:https://jsfiddle.net/p50e228w/6/

的问题是,我现在的JS适用于一审,但不是在其他。我目前有document.getElementsByClassName设置为“collies”,但我只需要在父类“dogs”类中使用该类。

我在这里错过了什么?

var span = document.createElement("span"); 
span.className = "paw-print"; 
var wrap = document.getElementsByClassName("collies"); 
for(var i = 0; i < wrap.length; i++) { 
    wrap[i].appendChild(span); 
} 

我可以使用jQuery的,但我一直在使用香草JS只是因为我这样的小白,想了解我的代码做什么。

+1

的问题是与你的'在CSS absolute'定位,JavaScript不 –

+0

我固定的CSS,使之更加精确。这里是更新的小提琴:https://jsfiddle.net/p50e228w/3/ ...但是,如果只是定位,我不会有多个跨度? – crezaii

+1

['.appendChild'](https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild)的问题是它不会_clone_元素。如果您引用现有跨度,则只会将其移至文档中的新位置。这就是为什么你的最终结果只有1跨度。 – Stryner

回答

2

有2个问题与您的代码。

  • 定位:图像被赋予绝对位置,并且它们基于页面布局放置在相同位置。所以设置父容器的相对位置。

CSS

.relative { 
    position: relative; 
} 
  • 您需要添加,为这collie这里父元素。

您可以使用querySelectorAll找到您正在寻找的嵌套关系。

Fiddle

+0

这是什么工作。谢谢! – crezaii

+0

@crezaii很高兴帮助! –

2

如果您要附加到父

$('.dogs .collies').each(function() // finds elements in the dom with parent element 'dog' and it's child element 'collies' 
{ 
    $(this) // 'this' would represent 'collies' element 
.closest('.dogs') // .closest('.dogs') would get it's nearest occurence in the heirarchy (basically it's parent) 
.append($('<span/>', { class: 'paw-print'})); // create a dynamic span element and append to 'this' 
}); 

如果要追加到孩子(带班“牧羊犬”元素)

$('.dogs .collies').each(function() 
{ 
    $(this).append($('<span/>', { class: 'paw-print'})); 
}); 

另外(带班“狗”元素)对此,您还需要设置由Rob指出的position: relative

例子:https://jsfiddle.net/DinoMyte/1zxn8193/1/

+0

你需要使父div相对于此位置工作,请参阅:https://jsfiddle.net/1zxn8193/ –

+0

是。感谢您指出了这一点。 – DinoMyte