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>
1

3 Answers 3

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"));
Sign up to request clarification or add additional context in comments.

Comments

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();

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.