2

How could I add a copy of the first tag at the end of an Array, since push() ,as I understand can't be used in this situation...

<p>A</p>
<p>B</p>
<p>C</p>

<script>
var pArray=document.getElementsByTagName("p");
//now I would like to add pArray[0]
</script>
Patrick
  • 17,669
  • 6
  • 70
  • 85
Robert002
  • 73
  • 1
  • 8
  • You may find this helpful http://stackoverflow.com/questions/2735067/how-to-convert-a-dom-node-list-to-an-array-in-javascript – Krasimir Sep 11 '13 at 21:35

3 Answers3

2

pArray isn't actually an array. It's a NodeList. To convert it into an array, just call Array.prototype.slice:

var pArray = Array.prototype.slice.call(document.getElementsByTagName("p"));
Blender
  • 289,723
  • 53
  • 439
  • 496
2

jsFiddle Demo

Push is not available because pArray is actually a NodeListMDN. However, you can add to it without using the array method push by simply assigning to the last index. cloneNodeMDN will copy the first element for you.

pArray[pArray.length] = pArray[0].cloneNode();
Travis J
  • 81,153
  • 41
  • 202
  • 273
1

If you want to actually add a copy of the first <p> tag to the DOM (rather than just modify an array), you’ll need to clone the node and insert it after the last node:

var els = document.getElementsByTagName('p');
var copy = els[0].cloneNode(true);
var last = els[els.length - 1];

last.parentNode.insertBefore(copy, last.nextSibling);
Todd Yandell
  • 14,656
  • 2
  • 50
  • 37