Home > Back-end >  Delete table row with JavaScript?
Delete table row with JavaScript?

Time:05-07

I am adding some data with JavaScript with no problem but I wanted to delete a row by adding delete button inside the row which I add, but I couldn't do it. The code is below. The delete button doesn't work:

const ad = document.querySelector("#ad");
const soyad = document.querySelector("#soyad");
const yas = document.querySelector("#yas");
const ekle = document.querySelector("#ekle");
const liste = document.querySelector("#liste");

ekle.onclick = function() {
  let tAd = document.createElement("td");
  let tSoyad = document.createElement("td");
  let tYas = document.createElement("td");
  let tSil = document.createElement("td");
  let silBtn = document.createElement("button");
  silBtn.textContent = "Sil";
  tAd.textContent = ad.value;
  tSoyad.textContent = soyad.value;
  tYas.textContent = yas.value;
  let tr = document.createElement("tr");
  tr.appendChild(tAd);
  tr.appendChild(tSoyad);
  tr.appendChild(tYas);
  tr.appendChild(silBtn);

  liste.appendChild(tr);
  ad.value = "";
  soyad.value = "";
  yas.value = "";
  ad.focus();

}
silBtn.onclick = function(e) {
  tr.appendChild(tAd);
  tr.appendChild(tSoyad);
  tr.appendChild(tYas);
  tr.appendChild(silBtn);
  liste.removeChild(this.parentNode.parentNode);
}
<div id="sayfa">
  <label for="">Ad:</label>
  <input type="text" id="ad">
  <label for="">Soyad</label>
  <input type="text" id="soyad">
  <label for="">Yas</label>
  <input type="text" id="yas">
  <button id="ekle">Tabloya Ekle</button>
  <table id="liste">
    <tr>
      <th>Ad</th>
      <th>SoyAd</th>
      <th>Yaş</th>
      <th>Sil</th>
    </tr>
  </table>
</div>

CodePudding user response:

Use This Javascript

<script>
const ad=document.querySelector("#ad");
const soyad=document.querySelector("#soyad");
const yas=document.querySelector("#yas");
const ekle=document.querySelector("#ekle");
const liste=document.querySelector("#liste");

ekle.onclick=function(){  
let tAd=document.createElement("td");
let tSoyad=document.createElement("td");
let tYas=document.createElement("td");
let tSil = document.createElement("td"); 
let silBtn =document.createElement("button");
silBtn.textContent="Sil";
tAd.textContent=ad.value;
tSoyad.textContent=soyad.value;
tYas.textContent=yas.value;
let tr=document.createElement("tr");
tr.appendChild(tAd);
tr.appendChild(tSoyad);
tr.appendChild(tYas);
tr.appendChild(silBtn);

liste.appendChild(tr);
ad.value="";
soyad.value="";
yas.value="";
ad.focus();
silBtn.onclick=function(e){ 
  liste.removeChild(this.parentNode); 
      }  
}
</script>
  • Related