/    Sign up×
Community /Pin to ProfileBookmark

Printing Just A Div Content With JS print()

How can I create a button when clicked, that just prints the content of a div, not the entire window? I tried:

onclick=”document.getElementById(“myDiv”).print();”

But I get object doesnt support this method. Is this possible?

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@Mr_JOct 01.2007 — Take a look at this example, see if it helps you out

www.huntingground.freeserve.co.uk/scripts/printing.htm
Copy linkTweet thisAlerts:
@WebnerdOct 01.2007 — <i>
</i>
function printSelection(node){

var content=node.innerHTML
var pwin=window.open('','print_content','width=100,height=100');

pwin.document.open();
pwin.document.write('&lt;html&gt;&lt;body onload="window.print()"&gt;'+content+'&lt;/body&gt;&lt;/html&gt;');
pwin.document.close();

setTimeout(function(){pwin.close();},1000);

}


Example:

<i>
</i>&lt;script type="text/javascript"&gt;

function printSelection(node){

var content=node.innerHTML
var pwin=window.open('','print_content','width=100,height=100');

pwin.document.open();
pwin.document.write('&lt;html&gt;&lt;body onload="window.print()"&gt;'+content+'&lt;/body&gt;&lt;/html&gt;');
pwin.document.close();

setTimeout(function(){pwin.close();},1000);

}
&lt;/script&gt;

&lt;div id="test"&gt;
this is a test

&lt;/div&gt;

&lt;a href="" onclick="printSelection(document.getElementById('test'));return false"&gt;print&lt;/a&gt;
×

Success!

Help @JustinK101 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...