let btn = document.querySelector('button'),
ul = document.getElementById('lista');
btn.onclick = () =>{
ele = ul.children[0].cloneNode(true, true);
ele.innerHTML = 'item #' + (ul.children.length +1)
ul.appendChild(ele);
}
Array.prototype.forEach.call(ul.children , child => {
child.onclick = () => {
document.getElementById('heading').textContent = child.textContent;
Array.prototype.forEach.call(ul.children, wald =>{
wald.classList.remove('active')
})
child.classList.add('active');
}
})
*{
padding: 0;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
.container{
width: 60%;
margin: 30px auto;
border: 1px solid;
padding: 30px 10px;
}
.container h1{
text-align: center;
background-color: tomato;
color: #fff;
}
.container button{
padding: 10px 20px;
background-color: tomato;
font-weight: bold;
font-size: 18px;
color: #FFF;
border: none;
cursor: pointer;
}
.container button:active{
transform: scale(.99)
}
.container ul li{
list-style-position: inside;
padding: 7px 15px
}
.active{
background-color: tomato;
color: #FFF;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Page Title</title>
<link rel="stylesheet" href="css/app.css" />
</head>
<body>
<div class="container">
<h1 id="heading">item here ! </h1>
<button>add item</button>
<ul id="lista">
<li>item #1</li>
<li>item #2</li>
<li>item #3</li>
</ul>
</div>
<script src="js/app.js"></script>
</body>
</html>
Cloned elements problem
The first event of this code to add new cloned elements to the <ul>
when I click the button.
The second event when I click on the li it suppose to have the class .active
.. but this second event only works with the original items not the new ones.
So what is the solution to attach the handler to new elements?