document.write blank page

Lamis Abouzina

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.

Quentin

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related