I have few spans:
<span name="5">a</span>
<span name="5">b</span>
<span name="5">c</span>
<span name="5">d</span>
I use getElementsByName
to get the span collection:
var spans = document.getElementsByName("5");
What I did next is clone the spans and put it into another span container:
var clonedSpan = spans.cloneNode(true);
var container = document.createElement("span");
container.appendChild(clonedSpan);
But the exception happens saying spans.cloneNode is not a function.
Any idea why?
CloneNode() It is a method used to clone an element from one list to another list. The cloneNode(), provided by javascript, the method creates a copy of a node and returns the clone. It can clone all attributes and their values.
You can easily change the DOM without having to edit the HTML as a big piece of string. Right click on a node and select Copy. You can paste in your code editor, or for prototyping, you can paste the DOM node elsewhere in the DOM tree.
The cloneNode() method creates a copy of a node, and returns the clone. The cloneNode() method clones all attributes and their values. Set the deep parameter to true if you also want to clone descendants (children).
cloneNode
is a method of an HTMLElement
, not of a NodeList
.
You have to call it on a single element:
var clonedSpan = spans[0].cloneNode(true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With