通过JS向特定的子元素添加HTML



我有一个非常具体的情况,我有~50个子div,我不能直接影响,也就是说,我不能添加类或id到一个特定的子div也不能通过HTML改变div,因为它们是自动创建的。它们出现在一个简单的网格/flexbox中,两个相邻的盒子。我已经用n -child修改了其中的一些,但是现在我想在f.ex之间添加单独的标题。Div 30和31.

到目前为止,当我想要一些更大的字段时,我直接通过n -child来处理其中一个子div。

下面是基本结构:
<div class="parent">
{$content} // basically <div>{$single-box-content}</div>
</div>

和我目前使用的CSS:

.parent {
width: 800px;
display: flex;
gap: 20px;
flex-wrap: wrap;
}

.parent:nth-child(10) {
width:800px;
}

效果很好。然而,现在我想有一个标题上面的div之一(而不是里面),它不工作。当我尝试这个:

.parent:nth-child(31):before {
content: "Headline";
display: block;
}

它出现在子div的内部,而不是上面。我不能在HTML部分添加div,因为所有这些都是在后端自动创建的(这是一个表单)。

我想知道是否有可能使用JavaScript与一些元素。innerHTML,但是我刚开始学习JS,我找不到任何(我可以适应)来解决JS中特定的子元素。我的问题是否有前端解决方案?

使用JS,您可以添加类,id,将html元素附加到DOM中等等。

下面向您展示了如何插入h2,以及如何向您选择的元素添加类-我使用:nth-child(3)用于说明目的,但您可以将其与:nth-child(31)交换。代码在代码片段的注释中进行了解释。

// finding the child element with nth-child selector
let selected = document.querySelector('.parent:nth-child(3)');
// giving it a class name
selected.classList.add('parentClass');
// creating a h2 element
let header = document.createElement("h2");
// the text inside the h2 element
let headerText = document.createTextNode("headline");
// appending the text to the h2 element
header.append(headerText);
// giving the child a class name
header.classList.add('childClass');
// appending the headline above/before the selected element 
selected.parentNode.insertBefore(header, selected);
/* the class applied with JS */
.parentClass {
background-color: red;
}
.childClass {
background-color: limegreen;
}
<div class="parent">parent 1</div>
<div class="parent">parent 2</div>
<div class="parent">parent 3</div>

最新更新