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";
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...
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');
I resolve similar problem with:
document.getElementById("xyz").style.padding = "10px 0 0 0";
Hope that helps.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With