skip to Main Content

a simple question: Based on the codes below, I would like to ask a question, is it possible for me to rewrite the elements using Javascript that were inside "person-infos" after having them removed by Javascript?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Testes</title>
</head>
<body>
  <div class="person-infos">
    <img class="photo">
    <div class="name"></div>
    <div class="age"></div>
  </div>

  <script src="testes.js"></script>
</body>
</html>
const infos = document.querySelector(".person-infos")
const nomeCandidato = document.querySelector(".name")
const partidoCandidato = document.querySelector(".age")

const elementsInfo = infos.children

infos.remove()

2

Answers


  1. If you mean you want to recreate those elements using Javascript after having them removed. You can use the createElement property on the document object to achieve that. Then append the created element to the div with class ‘person-infos’. A demonstration to that is.

    const infos = document.querySelector(".person-infos");
    
    // Create each child elements respectively
    const image = document.createElement("img")
    image.classList.add("photo");
    const name = document.createElement("div");
    name.classList.add("name");
    const age = document.createElement("div");
    age.classList.add("age");
    
    // Append those nodes to their parent element
    infos.appendChild("image");
    infos.appendChild("name");
    infos.appendChild("age");
    

    I hope this answers your question.

    Login or Signup to reply.
  2. Just as @Barmar said you can use createElement and appenChild to create and then append element into the DOM. If you want to add an element before others use prepend

    const infos = document.querySelector(".person-infos")
    const nomeCandidato = document.querySelector(".name")
    const partidoCandidato = document.querySelector(".age")
    
    const elementsInfo = infos.children
    
    infos.remove()
    
    let div = document.createElement('div')
    div.className = "person-infos"
    document.body.appendChild(div)
    let img = document.createElement('img')
    img.className = "photo"
    div.appendChild(img)
    let div2 = document.createElement('div')
    div2.className = "name"
    div.appendChild(div2)
    let div3 = document.createElement('div')
    div3.className = "age"
    div.appendChild(div3)
    let div4 = document.createElement('div')
    div4.className = "IamBefore"
    div.prepend(div4)
    <div class="person-infos">
          <img class="photo">
          <div class="name"></div>
          <div class="age"></div>
      </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search