jal
jal

Reputation: 533

DOM how to add more than one style in a div

I'm trying to add more than one style attribute using DOM setAttribute, but it doesn't work. How can I do it using JavaScript?

 var modificar = document.getElementById('opciones');
 modificar.setAttribute('style','float:left');
 modificar.setAttribute('style','margin:0px');

Upvotes: 0

Views: 188

Answers (4)

msturdy
msturdy

Reputation: 10794

There are two ways to do it:

modificar.style.setAttribute('float','left');
modificar.style.setAttribute('margin','0px');

or:

modificar.style.cssFloat  = 'left';
modificar.style.margin = '0px';

(edit: corrected to cssFloat in accordance with later posts)

Upvotes: 1

palaѕн
palaѕн

Reputation: 73976

You can set the class to the div like:

var modificar = document.getElementById('opciones');
x.className = "someClass";

and in the CSS, add as many style as you want like:

.someClass {
    float:left;
    margin:0px;
    color : red;
    ...
    ...
}

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075855

Use the style object on the element:

modificar.style.cssFloat = "left";
modificar.style.margin = "0px";

(Note that it's cssFloat, not float, from JavaScript. That's because float was a "future reserved word" in the ECMAScript specification 3rd edition [it no longer is in ES5], and you can't use reserved words when writing a property name in literal notation. So when defining the style object, they chose names like cssFloat when there was a conflict.)

For properties with dashes in them, you use camelCase instead:

modificar.style.backgroundColor = "#eee";

Upvotes: 3

ubik
ubik

Reputation: 4560

setAttribute is most likely working OK, but since you are invoking it twice, the result of the first call gets overridden by the second one.

Either do:

modificar.setAttribute('style','float: left; margin:0px;');

Or use the style attribute as suggested in another answer.

Upvotes: 3

Related Questions