私のプログラムでは、新たに作成されたdivをページに追加し、これらの新しいdivをMydivIDis1、MydivIDis2、MydivIDis3に。これらの新しく作成されたdivにはそれぞれ「削除」ボタンがあります。削除ボタンは現在あるdivを削除しますが、これを行う方法はわかりません。そのIDに基づいてdivを選択的に削除する関数を作成する方法
以下のコードでは、javascriptを使用して各div内に「要素を削除」ボタンを作成しようとしました。このボタンは、removeというonclick関数に関連付けられています。私は引数newDiv.idを取るためにbutton.onclickにも指定しています。しかし、このコードは動作しません。
<!DOCTYPE html>
<html>
<body>
<div id="MainContainer">
<input type="button" value="Add Element" id="add" onClick="add();">
<div id="InnerContainer">
</div>
</div>
<script>
var mainDiv=document.getElementById("MainContainer");
var innerDiv=document.getElementById("InnerContainer");
var clicks=0
var add=function(){
clicks += 1;
var newDiv=document.createElement("div");
newDiv.id="MydivIDis"+clicks;
newDiv.innerHTML=newDiv.id
mainDiv.appendChild(newDiv); //creates the new Div, with the id MydivIDis1, MydivIDis2, MydivIDis3
var button=document.createElement("button");
var t=document.createTextNode("Remove Element");
button.onclick=function(){
remove(newDiv.id); //Here i am trying to specify to the program to take newDiv.id as the input to the remove function.
};
button.appendChild(t); //creates new button and appends to each new Div
var remove=function(input){
mainDiv.removeChild(input);
}
mainDiv.appendChild(button);
};
</script>
</body>
</html>
['removeChild'](https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild)は、IDではなく引数としてノードを取っているようです。ですから、解決策は 'remove(newDiv.id)'を 'remove(newDiv)'に変更することだけかもしれません。 – Sevanteri
右。私は答えとして投稿します。 – Sevanteri