charan kamma charan kamma - 1 month ago 6
CSS Question

The margins in div of new tab not at all taking effect

Hi I am creating dynamic form in new tab using JavaScript. Margin effects on div are not taking effect. I am neither able to set the margins using class and id in css nor using div.setAttribute. Below is the code.
`

var openWindow = window.open('dynForm.html','_blank','');
var windoc=openWindow.document;
windoc.write("This is dynamic form ");
var div=document.createElement("div");
div.setAttribute("style","border:solid");
div.setAttribute("style","margin-left:1cm");
div.setAttribute("style","margin-right:1cm");
div.setAttribute("style","margin-bottom:1cm");
div.setAttribute("style","margin-top:1cm");
div.setAttribute("style","background-color:lightblue");


`Only background color is taking effect on the new tab. The below screen shot shows how the screen looks irrespective of the values of margin.enter image description here

Quesstion 2: No class or id attribute in my css is being applied to div.

#myDIV2{

background-color:lightblue;
}


I tried
div.id="myDIV2";


I also tried
div.setAttribute("id","myDIV2")
;` I applied the same using class also, but still couldn't find any difference. I do not know why its not working and what went wrong here. Please help

Answer

You're overriding the styles every time you call setAttribute, try combining the styles and then set the style attribute only once:

var openWindow = window.open('dynForm.html','_blank','');
    var styles= [
      "border:solid;",
      "margin: 1cm;",
      "background-color:lightblue;"
    ];
    var windoc=openWindow.document;
    windoc.write("This is dynamic form ");
    var end_styles = "";
    for (var i=0; i<styles.length;i++) {
        end_styles += styles[i];
    }
    var div=document.createElement("div");
    div.setAttribute("style", end_styles);

Note: the fiddle won't work on stackoverflow, I used it because it's easier to format code

Comments