Changing element style attribute dynamically using JavaScript

Changing element style attribute dynamically using JavaScript

I hav a certain style sheet for a div. Now i want to modify one attribute of div dynamically using js.
How can i do it?
document.getElementById(“xyz”).style.padding-top = “10px”;

Is this correct?

Solutions/Answers:

Solution 1:

It’s almost correct.

Since the - is a javascript operator, you can’t really have that in property names. If you were setting, border or something single-worded like that instead, your code would work just fine.

However, the thing you need to remember for padding-top, and for any hyphenated attribute name, is that in javascript, you remove the hyphen, and make the next letter uppercase, so in your case that’d be paddingTop.

There are some other exceptions. JavaScript has some reserved words, so you can’t set float like that, for instance. Instead, in some browsers you need to use cssFloat and in others styleFloat. It is for discrepancies like this that it is recommended that you use a framework such as jQuery, that handles browser incompatibilities for you…

Solution 2:

In addition to other answers, if you want to use the dash notition for style properties, you can also use:

document.getElementById("xyz").style["padding-top"] = "10px";

Solution 3:

I resolve similar problem with:

document.getElementById("xyz").style.padding = "10px 0 0 0";

Hope that helps.

Solution 4:

Assuming you have HTML like this:

<div id='thediv'></div>

If you want to modify the style attribute of this div, you’d use

document.getElementById('thediv').style.[ATTRIBUTE] = '[VALUE]'

Replace [ATTRIBUTE] with the style attribute you want. Remember to remove ‘-‘ and make the following letter uppercase.

Examples

document.getElementById('thediv').style.display = 'none'; //changes the display
document.getElementById('thediv').style.paddingLeft = 'none'; //removes padding

Solution 5:

document.getElementById("xyz").style.padding-top = '10px';

will be

document.getElementById("xyz").style["paddingTop"] = '10px';

Solution 6:

There is also style.setProperty function:
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty

document.getElementById("xyz").style.setProperty('padding-top', '10px');

// version with !important priority
document.getElementById("xyz").style.setProperty('padding-top', '10px', 'important');