Skip to content

Instantly share code, notes, and snippets.

@imparvez
Created July 8, 2019 18:02
Show Gist options
  • Save imparvez/1d1b48c9cac477625ca0dc038dbb23b7 to your computer and use it in GitHub Desktop.
Save imparvez/1d1b48c9cac477625ca0dc038dbb23b7 to your computer and use it in GitHub Desktop.
Clone Item with and without content using JavaScript
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="container">
<div class="col left-col">
<div class="item item-content">
clone with content
</div>
</div>
<div class="col right-col">
<div class="item item-no-content">
clone without content
</div>
</div>
</div>
</body>
</html>
window.onload = () => {
document
.querySelector('.item-content')
.addEventListener('click', onClickItemContent)
document
.querySelector('.item-no-content')
.addEventListener('click', onClickItemNoContent)
}
function onClickItemContent(event) {
const curElement = event.target
const clonedElement = curElement.cloneNode(true)
curElement.parentNode.appendChild(clonedElement)
}
function onClickItemNoContent(event) {
const curElement = event.target
const clonedElement = curElement.cloneNode(false)
curElement.parentNode.appendChild(clonedElement)
}
.container {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
background: #ccc;
}
.item {
padding: 20px;
border: 1px solid #fff;
background: purple;
color: white;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment