0

I have to apply multiple styles for a element, currently I have

document.getElementById("element1").style.top="1px";
document.getElementById("element1").style.marginLeft="0px";
|
|
|
document.getElementById("element1").style.left="10px";

How Can I do it in single line ? like

document.getElementById("element1").style={"top":"1px","left":"0px"};

I want to use plain Javascript not Jquery. Is it possible ?

user3191903
  • 237
  • 2
  • 6
  • 14

3 Answers3

2
document.getElementById("element1").style.cssText = "top: 1px; left: 0px;";

This should work but it would overwrite all existing inline defined styles.

Hope this helps.

nils
  • 1,668
  • 14
  • 15
2

To avoid overwriting your current classes you could do something like the following

document.getElementById("element1").style.cssText += "top: 1px; left: 0px;";

mcabrams
  • 686
  • 1
  • 6
  • 23
-1
  1. use JQuery library
  2. use css classes

Example:

<style>

.someClass {
   top: 1px;
   left: 0px;
}

</style>

<script>

$(document).ready(function(){

  $("#mydiv").addClass("someClass");

  $("#mydiv").removeClass("someClass");

});

</script>

<html>
<body>
<div id="mydiv"></div>
</body>
</html>

Good luck!

TchiYuan
  • 4,258
  • 5
  • 28
  • 35