0

I want create div inside another div using. Please tell me where am going wrong.

   window.onload =function() {
    var child = document.createElement('div');
    child.id = 'blockid';
    child.className = 'blockclass';
    
    var s = document.getElementById('parent');
    s.appendChild(child); 
    document.getElementById("blockid").innerHTML = "hi";
    }
    
<div id="parent">Test</div>

3
  • 1
    I don't see the problem. In the code you shared blockid is inserted inside parent. Do you expect parent to cinain only the div and not Hi anymore ? Commented Jul 16, 2015 at 7:49
  • @ ANI: That code should be fine (although you don't need the last document.getElementById, just use child). So we need more information to be able to help you. Commented Jul 16, 2015 at 7:50
  • Works for me Commented Jul 16, 2015 at 7:50

1 Answer 1

1

I think you may be getting mislead by how the result looks:

Test
hi

That makes it look like they're stacked, but they're not, your code is working fine. The second div is inside the first, after the text.

Adding borders and padding can make that clearer:

window.onload = function() {
  var child = document.createElement('div');
  child.id = 'blockid';
  child.className = 'blockclass';

  var s = document.getElementById('parent');
  s.appendChild(child);
  document.getElementById("blockid").innerHTML = "hi";
};
#parent {
  border: 1px solid blue;
  padding: 4px;
}
#blockid {
  border: 1px solid green;
}
<div id="parent">Test</div>

Note, though, that you don't need the document.getElementById at the end, you can use child:

window.onload = function() {
  var child = document.createElement('div');
  child.id = 'blockid';
  child.className = 'blockclass';

  var s = document.getElementById('parent');
  s.appendChild(child);
  child.innerHTML = "hi"; // <== Changed
};
#parent {
  border: 1px solid blue;
  padding: 4px;
}
#blockid {
  border: 1px solid green;
}
<div id="parent">Test</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.