5

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?

Ferrmolina
  • 2,737
  • 2
  • 30
  • 46
typeof programmer
  • 1,509
  • 4
  • 22
  • 34
  • `getElementsByName` return a `NodeList`. `cloneNode` expects a `Node`. You probably want to clone the first/unique element within that list. – Jeto Jul 20 '18 at 17:46
  • use this code to clone all nodes: `var clonedSpan = Array.from(spans).map(function(node){return node.cloneNode(true);}` – Kavian Rabbani Jul 20 '18 at 17:54

1 Answers1

10

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);
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
BenM
  • 52,573
  • 26
  • 113
  • 168