[英]Adding new element to nested classes
我需要使用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,只是因为我是一个菜鸟,想了解我的代码在做什么。
如果要追加到父项(元素为“狗”的元素)
$('.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'
});
如果要追加到child(类为'collies'的元素)
$('.dogs .collies').each(function()
{
$(this).append($('<span/>', { class: 'paw-print'}));
});
除此之外,您还需要设置position: relative
Rob指出的position: relative
。
您的代码有2个问题。
位置:图像被赋予绝对位置,并且根据页面布局它们位于相同的位置。 因此,请为父容器设置相对位置。
的CSS
.relative {
position: relative;
}
collie
父元素。 您可以使用querySelectorAll
查找所需的嵌套关系。
var collies = document.querySelectorAll('.dogs .collies');
for (var i = 0; i < collies.length; i++) {
var span = document.createElement("span");
span.className = "paw-print";
collies[i].appendChild(span);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.