How to print multiple nested divs

Hi guys , I am new here :smiley:

could you please help me in this:

I have multiple divs something like this

<div id=“div1”>
<div id=“div2”>
<div id=“div3”>

</div>
</div>

I want JavaScript code to print div1 with all nested divs as well

I tried using the following code but it only print div1 content :frowning:

var printContent = document.getElementById('div1');
var windowUrl = 'about:blank';
var uniqueName = new Date();
var windowName = 'Print' + uniqueName.getTime();
var printWindow = window.open(windowUrl, windowName, 'left=50000,top=50000,width=200,height=200');

printWindow.document.write(printContent.innerHTML);
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();

so please tell me how to do such operation ??

printWindow.document.write(printContent.innerHTML);

please note, printContent is a string so .innerHTML is not a property.

The easiest way is to use a function that calls itself to traverse the DOM (Document object model) that is your HTML page. This needs to be done after the page has loaded.

<html>
<head>
<script type="text/javascript">
<!--

function nesteddivs (thisnode) {
	var divrecord = "";
	var children = thisnode.childNodes;
	for (var i=0; i<children.length; i++) {
		var child = children[i];
		if (child.tagName == "DIV") {
			if (child.id) {
				divrecord = divrecord + "<li>" + child.id + "</li>" + nesteddivs(child);;
			}
		}
	}
	return divrecord;

}

function examinedivs (thisdiv) {

var rootdiv = document.getElementById(thisdiv);

var printContent = '<ul>' + nesteddivs(rootdiv) + '</ul>';
var windowUrl = 'about:blank';
var uniqueName = new Date();
var windowName = 'Print' + uniqueName.getTime();
var printWindow = window.open(windowUrl, windowName, 'width=200,height=200');

printWindow.document.write(printContent);
printWindow.document.close();

}
/ -->
</script>
</head>
<body onload="examineedivs('div1')">
<div id="div1">div1
	<div id="div1a">div1a
		<div id="div1ai">div1ai</div>
		<div id="div1aii">div1aii</div>
		<div>div1aiii</div>
		<div id="div1aiv">div1aiv</div>
		<div id="div1av">div1av</div>
	</div>
	<div id="div1b">div1b
		<div id="div1bi">div1bi</div>
	</div>
</div>
<div id="div2">
</div>
</body>
</html>

The function examineedivs is called from the body onload event. Its argument is the id of the root element, in this case “div1”. It locates the div and calls a function nesteddivs which forms a list of all the divs with an id that are descendants of the div.