Reinserting elements elsewhere in Body, html and Javascript

Asked

Viewed 71 times

0

I’m trying to store in a var, and then reinsert into the body 3 elements of the type "p".

<body>

<p> Um</p>
<p> Dois </p>
<p> Tres </p> ....

In doing so:

<script>
    var parag = document.querySelectorAll("p");
        document.write(parag);
</script>

What I have printed on the screen is a kind of "label" or object list name (for DOM, or elements, pro html, correct?) "p":

Print like this:

[Object Nodelist]

Now, is there any way I can get those elements "p", and effectively reprint its contents in the body??

  • querySelectorAll return a NodeList logo to use each of the elements needs a for. A short time ago I answered a question very similar to yours if not duplicated. See here

1 answer

1


When using document.querySelectorAll will generate an object with a collection of nodes (nodes) of the selected elements in the selector, in its case the "p" (tag <p>).

To reprint them using document.write you can use a loop for taking the HTML of each item in the collection with outerHTML. There are other ways to insert the items on the page, but using document.write could be this way:

var parag = document.querySelectorAll("p");

for(var x=0; x<parag.length; x++){
   document.write(parag[x].outerHTML);
}
<p> Um</p>
<p> Dois </p>
<p> Tres </p>

You can also clone the elements and reinsert the page using the method cloneNode:

var parag = document.querySelectorAll("p");
for(var x=0; x<parag.length; x++){
   var clone = parag[x].cloneNode(true); // true quer dizer selecionar tudo do elemento
   document.body.appendChild(clone);
}
<p> Um</p>
<p> Dois </p>
<p> Tres </p>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.