I would like to know why I am having this error
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
printDiv(printableArea);
<body>
<div id="printableArea" style="display: none;">
<h1>Print me</h1>
</div>
</body>
And I have this error:
Cannot read property 'innerHTML' of null at printDiv (first.html:48) at first.html:58`
This is line 48:
var printContents = document.getElementById(divName).innerHTML;
And this is 58:
printDiv(printableArea);
The error is here:
There is no variable
printableArea
. But if there is an element withID
equal toprintableArea
.Solution:
Actually the error I think is quite explicit:
Which means you're trying to use
innerHTML
on a null element.The error is not really given by line 58 but by line 48, in which you try to perform the following action:
Of course, you can't modify the HTML of an element that doesn't exist, so that's why you get the error, because
divName
it would have to be an ID and you're passingdivName
the variableprintableArea
(which doesn't exist) instead of an IDThe method syntax
getElementById
is as follows:in which
elementID
it has to be aString
that represents the ID of an element of the page.Therefore, the correction to your problem would be made on line 58, in which you pass the parameter to the function
divName
, passing theString
ID instead of a variable that doesn't exist.Of course, you could also do the following in case you wanted to use a variable:
Validate first that the element exists:
Modify your code as follows: