-2

I would like to set up an HTML page programmatically using JavaScript but I am running into a styling issue with margins. Here's a minimal example:

window.onload = function() {

  var div0 = document.getElementById('box2');
  div0.style.border = '1px solid black';

  var div1 = document.createElement('div');
  div0.appendChild(div1);
  div1.innerHTML = "This is programmatic";
  div1.style.width = '300px';
  div1.style.height = '200px';
  div1.style.background = 'pink';
  div2.style.marginTop = '20px';
  div2.style.marginLeft = '20px';
};
<div id="box1" style="border:1px solid black">
  <div style="width:300px;height:200px;background:lightgreen;margin-left:20px;margin-top:20px">
    This is regular styled HTML</div>
</div>
<div id="box2"></div>

This displays as follows:

Margin styles not operating

The programmatic version (pink) appears to be ignoring the margins. Is there something different about an element that's created programmatically? I can see no differences in the styles reported for the 2 divs.

j08691
  • 204,283
  • 31
  • 260
  • 272
Graham
  • 107
  • 2
  • 8
  • 1
    Your snippet is getting an error for the undefined `div2`. – Barmar Dec 14 '18 at 22:08
  • This is just a typo. Fix it and the problem goes away. If you are going to be doing any javascript work, you should learn to use the browser's error console before you go any further. It will save you a lot of time. – Mark Dec 14 '18 at 22:09
  • Thanks guys - I just spotted it after I posted. Stupid mistake. – Graham Dec 14 '18 at 22:09

2 Answers2

1

Its because you were referencing a variable called div2 - which does not exist - if you change that to div 1 - then it works fine.

<html>
  <head>
    <title></title>
    <meta content="">
    <style></style>
    <script>
        window.onload = function () {

            var div0 = document.getElementById('box2');
            div0.style.border='1px solid black';

            var div1 = document.createElement('div');
            div0.appendChild(div1);
            div1.innerHTML="This is programmatic";
            div1.style.width='300px';
            div1.style.height='200px';
            div1.style.background='pink';
            div1.style.marginTop='20px'; // I altered this line
            div1.style.marginLeft='20px'; // I altered this line
        };
    </script>
  </head>
  <body>
    <div id="box1" style="border:1px solid black">
      <div style="width:300px;height:200px;background:lightgreen;margin-left:20px;margin-top:20px">
        This is regular styled HTML</div>
      </div>
    <div id="box2"></div>
  </body>
</html>
gavgrif
  • 15,194
  • 2
  • 25
  • 27
1

Change div2 to div1 and it's gonna work. There was a hint in console: index.html:18 Uncaught ReferenceError: div2 is not defined at window.onload

Bonus:

Define your classes in css files and from JS, just add them like this:

div1.classList.add('myClass')
Tomasz Bubała
  • 2,093
  • 1
  • 11
  • 18