creating a new element in the html dom using foreach and assigning a class to it

412 Views Asked by At

i have an html structure, I want to change the text element using javascript in this structure, I want to create a new element and add a class in it. But it doesn't work

HTML CODE

<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 CODE

<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>

am i using foreach incorrectly i need to open a different for each

1

There are 1 best solutions below

1
Nick On BEST ANSWER

You need to create the span in the document and then append it to 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>