find and solve || findandsolve.com
Please wait.....

Welcome back.






Before Read Terms of use

Uncaught TypeError: Cannot set property ‘innerHTML’ of null

Uncaught TypeError: Cannot set property ‘innerHTML’ of null

You can see this in the top right corner of the inspect page. When I click on that the full error is shown in the console.

This is my htm code as given below

 <button onclick="print('print_all')" class="btn btn-primary">
   <i class="fa fa-print"></i>
 </button>
<div id="print_all">
<div class="row">
<div class="col-sm-12">
<h1>InnerHtml issue print</h1>
</div>
</div>
</div>

Here my javascript

<script type="text/javascript">
function print(divName,) {        
   var printContents = document.getElementById(divName).innerHTML;     var originalContents = document.body.innerHTML;     document.body.innerHTML = printContents;     window.print();     document.body.innerHTML = originalContents; </script>


Answer

Option 1.

If you use Asp.Net MVC the you can easly use like this

@section scripts {
    <script type="text/javascript">
            function print(divName) {
                var printContents = document.getElementById(divName).innerHTML;
                var originalContents = document.body.innerHTML;
                document.body.innerHTML = printContents;
                window.print();
                document.body.innerHTML = originalContents;
            }
    </script>
}

in other case

<script type="text/javascript">
    $(document).ready(function () {
        function print(divName) {
            var printContents = document.getElementById(divName).innerHTML;
            var originalContents = document.body.innerHTML;
            document.body.innerHTML = printContents;
            window.print();
            document.body.innerHTML = originalContents;
       }
    });
</script>

Option 2.

document.addEventListener("DOMContentLoaded", function(event) { 
    //Do work here
});

Option 3.

Check your html id as like that and call the fuction if your html is not null as give below.

if(document.getElementById("print_all") != null){
    var idPost=document.getElementById("print_all").innerHTML;
}

Option 4.

window.onload = function(){
    function print(message) {
        document.getElementById(message).innerHTML
    }
}

Option 5.

     function print(divName) {
        var myElement= document.getElementById(divName);
         if (myElement!=null) {
            //the working here
        }
      else
      {
        //in the null case here
      }
}

Mahira  khanna

Mahira khanna

I have the skills you need for you company blog, website, or other content materials

Comments



Report Response