Home > Software design >  creating a new element in the html dom using foreach and assigning a class to it
creating a new element in the html dom using foreach and assigning a class to it

Time:10-11

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 >
   <div >2022</div>
        <h3 >
         <a href="#" target="_self">Sirena Yachts</a>
        </h3>
   <div >
    <p>YEAR : 2022 LOCATION</p>
   </div>
 <a href="#"  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

CodePudding user response:

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 >
  <div >2022</div>
  <h3 >
    <a href="#" target="_self">Sirena Yachts</a>
  </h3>
  <div >
    <p>YEAR : 2022 LOCATION</p>
  </div>
  <a href="#"  target="_self">READ</a>
</div>

  • Related