I have two div tags like bellow:
<body>
<div id="divParent">
<div id="divChild"></div>
</div>
</body>
How can I get the divChild using JavaScript?
I have two div tags like bellow:
<body>
<div id="divParent">
<div id="divChild"></div>
</div>
</body>
How can I get the divChild using JavaScript?
Share Improve this question edited Oct 25, 2012 at 7:46 Shiplu Mokaddim 57.7k20 gold badges145 silver badges192 bronze badges asked Oct 25, 2012 at 7:39 MJ_DeveloperMJ_Developer 5461 gold badge3 silver badges16 bronze badges 3- Will your actual elements have IDs or is this just for demo purposes and you want to traverse the DOM? – m90 Commented Oct 25, 2012 at 7:43
- Read this developer.mozilla/en-US/docs/DOM/document.getElementById – Shiplu Mokaddim Commented Oct 25, 2012 at 7:46
- @MJ_Developer updated answer to show how to hide/show child div – vdbuilder Commented Oct 25, 2012 at 7:58
4 Answers
Reset to default 6Use this:
divChild = document.getElementById("divChild");
or if you didn't have the child id:
divChild = document.getElementById("divParent").children[0];
Edit:
you can hide or show child with:
divChild.style.display = "none";//hide
divChild.style.display = "block";//show
var myDiv = document.getElementById('divChild');
Then you can get the contents like this
var content = myDiv.innerHTML;
var el = document.getElementById("divChild")
var div = document.getElementById("divChild");