I have a page that has a DIV within another DIV. What I am trying to do is change the HTML of the inner DIV but I keep getting a JavaScript error saying the inner DIV has no properties. I thought access to a page element by its ID always worked. Can someone point out to me where my error in logic is here?
Thanks
<html>
<head>
<style type="text/css">
.container
{
position: absolute;
top: 80px;
left: 210px;
height: 400px;
width: 600px;
border-color: red;
border-style: solid;
background-color: #ffffff;
padding: 20px 10px 20px 10px;
font-family:verdana,sans-serif;
font-size:18pt;
text-align: center;
z-index: 2000;
}
.innerBottom
{
position: absolute;
height: 50px;
width: 90%;
border-color: blue;
border-style: solid;
bottom: 10px;
left: 5%;
}
</style>
<script language="JavaScript">
function buildDIVs()
{
addPageMarkup();
document.getElementById( "containerDiv" ).innerHTML = "Container text";
// this line not working
document.getElementById( "innerDiv" ).innerHTML = "Inner Div text";
}
function addPageMarkup()
{
var body = document.getElementsByTagName( 'body' ).item(0);
var containerDiv = document.createElement( 'div' );
containerDiv.id = "containerDiv";
containerDiv.className = "container";
var divBottom = document.createElement( 'div' );
divBottom.id = "innerDiv";
divBottom.className = "innerBottom";
containerDiv.appendChild( divBottom );
body.appendChild( containerDiv );
}
</script>
</head>
<body>
<a href="javascript: buildDIVs();">Build DIVs</a>
</body>
</html>
Thank you for the assistance. What I ended up doing is adding a top div that contains the top text. Below is the code.
If you also don’t mind, why is innerHTML on the container DIV hosing the bottom div? The way I understand innerHTML is that it sets HTML between the start and end tags of the object. I did not realize that this over wrote anything else added to the object.
Thank you for the information. I will have to do more research on the insertBefore method since I was not aware of it. Would you say it is more of an industry trend to use insertBefore instead of creating 2 DIVs within the container div like my previous example shows? I am starting to research more and more about object oriented JavaScript and making the widgets self contained so the more industry standard information I can acquire, the better. Thanks for your time and knowledge regarding this.
A child is a level below the element it is being appended to. So, divBottom is created inside the div of containerDiv rather than after it. As a result, containerDiv.innerHTML replaces the enclosed divBottom. What you want is: