Reinserting elements in another part of Body, html and Javascript

0

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

<body>

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

When you do this:

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

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

Print like this:

[object NodeList]

Now, how can I get these elements " p ", and effectively reprint in body its contents ??

    
asked by anonymous 11.04.2018 / 14:47

1 answer

1

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

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

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 cloneNode method:

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>
    
11.04.2018 / 15:29