使用foreach在htmldom中创建一个新元素,并为其分配一个类



我有一个html结构,我想在这个结构中使用javascript更改文本元素,我想创建一个新元素并在其中添加一个类。但它不起作用

HTML代码

<div class="project-list-content">
<div class="project-list-category">2022</div>
<h3 class="project-list-title">
<a href="#" target="_self">Sirena Yachts</a>
</h3>
<div class="project-list-excerpt">
<p>YEAR : 2022 LOCATION</p>
</div>
<a href="#" class="project-list-link a-btn-arrow-2" target="_self">READ</a>
</div>

JAVASCRIPT代码

<script>
let read = document.querySelectorAll(".project-list-content > a");
var read_array = [...read];
read_array.forEach(read => {
read.textContent = "INCELE";
let newSpan = read.createElement("span");
newSpan.classList.add("arrow-right");
});
</script>

我是否错误地使用foreach,我需要为每个打开不同的

您需要在document中创建span,然后在append中将其创建为read:

let read = document.querySelectorAll(".project-list-content > a");
var read_array = [...read];
read_array.forEach(read => {
read.textContent = "INCELE";
let newSpan = document.createElement("span");
newSpan.classList.add("arrow-right");
read.append(newSpan)
});
.arrow-right::after { content: 'right-arrow'; }
<div class="project-list-content">
<div class="project-list-category">2022</div>
<h3 class="project-list-title">
<a href="#" target="_self">Sirena Yachts</a>
</h3>
<div class="project-list-excerpt">
<p>YEAR : 2022 LOCATION</p>
</div>
<a href="#" class="project-list-link a-btn-arrow-2" target="_self">READ</a>
</div>

相关内容

  • 没有找到相关文章

最新更新