'Clone an element with an specific attribute with Vanilla JS
I'm trying to clone an element with a specific attribute that I've set via JS. The code:
HTML
<div id="container">
<div class="test" data-test></div>
<div class="test" data-test data-cloneable></div>
<div class="test" data-test></div>
</div>
<div>
<button data-tool="clone">Clone</button>
</div>
One of those elements have an data-cloneable attribute that I'm checking with JS:
JavaScript
var container = document.getElementById("container");
var elements = document.querySelectorAll("[data-test]");
Array.prototype.forEach.call(elements, function(element) {
cloneTool = document.querySelector("[data-tool='clone']");
cloneTool.onclick = function() {
var clone = element.cloneNode(true);
if(element.hasAttribute("data-cloneable")) {
container.appendChild(clone);
}
};
});
It's not working, ahh, more or less, the problem is that command only clones the last element in the container and not the specific element.
Solution 1:[1]
Something like this? Or do you mean that the clone would appear just under its origin?
http://jsfiddle.net/omikey/nupc7htn/2/
var cloneTool = document.querySelector("div[data-cloneable='true']");
cloneTool.onclick = function(clone) {
var node = this.cloneNode(true);
var container = document.getElementById('container');
container.appendChild(node);
};
<div id="container">
<div class="test">1</div>
<div class="test" data-cloneable="true">2</div>
<div class="test">3</div>
</div>
Solution 2:[2]
One problem with your code is the event registration, since you are using onclick property in each iteration you are overriding the previously assigned click handler.
So at the end of the loop the only handler that is present is the one corresponding to the last data-test element, which when triggered does not have the data-clonable attribute so nothing happens.
Do you mean something like
var container = document.getElementById('container');
var cloneTool = document.querySelector("[data-tool='clone']");
cloneTool.addEventListener('click', function() {
var elements = document.querySelectorAll("[data-test][data-cloneable]");
Array.prototype.forEach.call(elements, function(element) {
container.appendChild(element.cloneNode(true));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
<div class="test" data-test>1</div>
<div class="test" data-test data-cloneable>2</div>
<div class="test" data-test>3</div>
</div>
<div>
<button data-tool="clone">Clone</button>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | omikes |
| Solution 2 |
