Density
Density

Reputation: 91

Javascript .style in document.createElement not working

This is my code:

        var link = document.createElement("a");
        link.id = "control_random";
        link.href = document.location.href + "#";
        //link.style = "margin-left:200px";

The code marked with the // doesn't work. And when I edit it using inspect element I notice that it hasn't been applied.

Upvotes: 0

Views: 59

Answers (2)

Krishanu Dey
Krishanu Dey

Reputation: 6406

You must use style.cssText

var link = document.createElement("a");
link.id = "control_random";
link.style.cssText = "margin-left:200px; margin-right:100px;";

Other Ways...

link.setAttribute("style", "margin-left:200px; margin-right:100px;");

(Thanks to @ T.J. Crowder)

link.style.marginLeft = "200px";
link.style.marginRight = "100px";

Upvotes: 3

Vishu238
Vishu238

Reputation: 673

Use this

link.style.margin = "200px";

also

link.style.marginLeft ="200px"

or simply use .cssText = "your css"

check this
Click here to view demo! Updated link updated link!

Upvotes: 0

Related Questions