Based on DucFilan's and Frankusky's suggestions,
After getting the data which is needed to be printed, append that data to some div and hide other elements expect the div to which you appended the data. And after printing the data, show hidden elements and hide the data div like below,
var printContents = document.getElementById('print_data').innerHTML;
document.getElementById('printContents').innerHTML = printContents;
var allElements = document.body.children;
for(var i = 0; i < allElements.length; i++) {
if(allElements[i].getAttribute('id') !== "printContents") {
allElements[i].style.display = "none";
}
}
window.print();
for(var i = 0; i < allElements.length; i++) {
if(allElements[i].getAttribute('id') !== "printContents") {
allElements[i].style.display = "block";
} else {
allElements[i].style.display = "none";
}
}
Working example - https://jsfiddle.net/totpvcrh/1/
Note: In the fiddle, after closing the print dialog, you will get message below the open modal button. No need to bother about that. In website it is working fine.