1

I am trying to run this code to get the elements from the paragraph in my HTML code and display:

<!DOCTYPE html>
<html>
<body>

<p>This is a p element<br>

This is also a p element.<br>

This is also a p element - Click the button to change the background color of all p elements in this document.</p>

<button onclick="myFunction()">Try it</button>

<script>
    function myFunction() {
        win = window.open();
        win.document.open();
        var x = document.getElementsByTagName("p");
        for (var i = 0; i < x.length; i++) {
            win.document.write(document.getElementById(x.item(i).id).innerHTML);
        }
    }
</script>

</body>
</html>

I don't know how, but I keep getting a blank window. Any help?

Thank you.

Roland Rácz
  • 2,879
  • 3
  • 18
  • 44
Lamis Abouzina
  • 369
  • 1
  • 3
  • 16
  • `document.write` writes over the page, you don't want to ever be using that as it's bad and outdated – Sterling Archer Feb 23 '18 at 15:42
  • @SterlingArcher — `document.write` is being called in the new window where there isn't a document. The question says the document is *blank* not that the existing content is overwritten by the new content. – Quentin Feb 23 '18 at 15:44
  • @SterlingArcher Correctly used, there are many/some possible applications (e.g. https://stackoverflow.com/a/1014251/402037) – Andreas Feb 23 '18 at 15:48

1 Answers1

0

Your paragraph doesn't have an id.

So when you read its id property you get undefined.

When you call document.getElementById(undefined) you get null.

When you read null.innerHTML, you get an error.


You already have the element. Don't try to get the ID from the element so that you can get the element.

That is like reading the Dewey Decimal code from a book in your hands so you can go to the shelf it lives on so you can read it.

Also, don't use item(), just treat the node list as an array.

win.document.write(x[i].innerHTML);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • yes perfect it worked ! thank you but here's my problem is i add an alignment Style it doesn't reflect in the new open window! and that's my main problem any idea how to fix that ? – Lamis Abouzina Feb 23 '18 at 15:54