How to print div content using jQuery?

jQueryWeb DevelopmentFront End Technology

Let’s say we have the following button −

<input type='button' id='buttonId' value='Press Me To print the data'>

On click of the above button, call the function() with on() −

$('#buttonId').on('click', function () {
   displayTheData();
})

The above function is using the html() to display the following div −

<div id='printThisDivIdOnButtonClick'>
   <p>I am inside the div tag...</p>
</div>

Example

Following is the complete code to print div content −

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<body>
   <div id='printThisDivIdOnButtonClick'>
      <p>I am inside the div tag...</p>
   </div>
   <p>I am not inside the div tag...</p>
   <input type='button' id='buttonId' value='Press Me To print the data'>
   <div id="printTheDivisionValue"></div>
</body>
<script>
   $('#buttonId').on('click', function () {
      displayTheData();
   })
   function displayTheData() {
      $(document).ready(function () {
         $("#printTheDivisionValue").html($("#printThisDivIdOnButtonClick").html());
      });
   }
</script>
</html>

To run the above program, save the file name anyName.html (index.html). Right click on the file and select the option “Open with Live Server” in VS Code editor.

Output

The output is as follows −

Now click the button, you will get the following output.

The output is as follows −

raja
Published on 01-Oct-2020 13:33:17
Advertisements