I am trying to make a button that creates small windows that you can close after pressing X. The problem I have is that i can only close the last created window.
function openNote() {
var base = document.createElement('div');
base.id = 'note';
var in_ = document.createElement('div');
in_.id = 'note_in';
var in_2 = document.createElement('div');
in_2.id = 'note_in2';
var ex = document.createElement('div');
ex.id = 'ex';
var ext = document.createTextNode("X");
base.appendChild(in_);
in_.appendChild(in_2);
in_2.appendChild(ex);
ex.appendChild(ext);
document.body.appendChild(base);
document.getElementById('ex').onclick = function(){
var r = document.getElementById('note');
r.parentNode.removeChild(r);
}
}
#note{
background:#819C9A;
height : 200px;
width : 150px;
border: 2px solid;
border-radius: 25px;
border-color:#49706E;
margin:10px;
}
#note_in{
float:left;
height : 35px;
width : 150px;
background:rgba(255,255,255,0.2);
}
#note_in2
{
float:right;
height : 25px;
width : 25px;
margin:5px;
background:#9DCCCA;
border-radius: 15px;
text-align: center;
cursor:pointer;
}
#ex{
margin-top: 4px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="script.js"></script>
</head>
<body>
<button onClick="openNote();">Press me!</button>
</body>
</html>
I'm fairly new to JavaScript and would appreciate any help or advice.
Problem you are facing is that you create more than one dom element with same id, id is unique per page.
What happens now is every time when you click 'Press me!' new dom element is created, but the document.getElementById('ex') only gets the first in the tree so you are always binding event to the first element no matter how many you add later.
Options for fixing would be few:
Using 3rd option you could actually skip all id's