简体   繁体   中英

Unable to print div's content using Javascript

I'm trying to print the content of a div when the "Print" button is clicked. I keep getting this error: "Unable to set value of the property 'innerHTML': object is null or undefined." I read some posts over the Internet but I still can't find a working solution.

Here is my javascript code I use to print (got from here ):

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

        document.body.innerHTML = printContents;

        window.print();

        document.body.innerHTML = originalContents;
    }
</script>

My button event raises here:

<asp:Button ID="ButtonPrint" runat="server" Text="Print »" OnClientClick="printDiv('content');return false"></asp:Button>

And this is the div I'm supposed to print:

 <div id="content" runat="server">
    <h1 class="title" runat="server" id="formulario"></h1>
    <asp:Table ID="TableForm" runat="server"></asp:Table>
    <div id="TableQuest" runat="server">
    </div>
    <asp:Table ID="TableText" runat="server"></asp:Table>
   <asp:Label ID="LabelInfo" runat="server" Text=""></asp:Label>
</div>   

Any help would be greatly appreciated!

Thanks to @ Evan Knowles I finally found a solution.

I'm actually using a MasterPage and Content Pages, so my id's name 'content' is automatically changed in 'ContentPlaceHolder1_content'.

If the method is called using the new generated id: <asp:Button ID="ButtonStampa" runat="server" Text="Stampa »" OnClientClick="printDiv('ContentPlaceHolder1_content');return false"></asp:Button> everything works just fine!

You should use - <%=content.ClientID()%>

your Div is server side so you will not get this div as you mention in your question. You have to use .ClientID as below code.

document.getElementById('<%=content.ClientID %>').innerHTML

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM