Display div element content in a new popup window – JavaScript

By Faruque Ahamed Mollick

In this post, I am going to show you how to display the content of a div element in a new popup window in JavaScript.

Before we going to see how to open and show our div element content in the new window, let’s create our HTML:

  <h1>Open the element content when click the button</h1>
<div id="myContent">
  This is the content that will be inside the new popup window
</div>
<button id="mybtn">open</button>

From the above HTML content, we are going to show the content from div element ID “myContent”. We have also created a button with the ID “mybtn”.

On clicking the button, we are going to open our new window which holds only the content from the div ID “myContent”.

Now, let’s see our JavaScript code:



document.getElementById("mybtn").addEventListener("click", function(){ 
         var newWindowContent = document.getElementById('myContent').innerHTML;
         var newWindow = window.open("", "", "width=500,height=400");
         newWindow.document.write(newWindowContent);
 });

In the above JavaScript code, we apply the click event listener to the button so that clicking the button open our new popup window.

We have taken the content of the div element inside a variable and write it into our new popup window. To open the new popup window, we have used the JavaScript window open() method. You can see that we have first take the method into a variable. We also have set the width and height of our window.

 

Also, read:

 

After that, we use the document.write() method to write our div element content into the new popup window. Our div element content that we want to show on new popup window is already in our variable. So we just have to pass the variable inside the document write() method what we did in the code above.

Now let’s test the code on your browser. if everything’s goes right, then you should see a new popup window open with the content of the div element when you click the button.

So we have learned how to display div element content in a new popup window.

Leave a Reply

Your email address will not be published. Required fields are marked *