Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript cloneNode is not a function [duplicate]

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?

like image 918
typeof programmer Avatar asked Jul 20 '18 17:07

typeof programmer


People also ask

What is cloneNode in JavaScript?

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.

How do I copy a DOM?

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.

How do you copy a node element?

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).


Video Answer


1 Answers

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);
like image 144
BenM Avatar answered Oct 01 '22 02:10

BenM