[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?

This question is related to javascript html css

The answer is


I would recommend using a function, which accepts the element id and an object containing the CSS properties, to handle this. This way you write multiple styles at once and use standard CSS property syntax.

//function to handle multiple styles
function setStyle(elId, propertyObject) {
    var el = document.getElementById(elId);
    for (var property in propertyObject) {
        el.style[property] = propertyObject[property];
    }
}

setStyle('xyz', {'padding-top': '10px'});

Better still you could store the styles in a variable, which will make for much easier property management e.g.

var xyzStyles = {'padding-top':'10px'}
setStyle('xyz', xyzStyles);

Hope that helps


Surprised that I did not see the below query selector way solution,

document.querySelector('#xyz').style.paddingTop = "10px"

CSSStyleDeclaration solutions, an example of the accepted answer

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

I resolve similar problem with:

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

Hope that helps.


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');

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";

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

I change css style in Javascript function.

But Uncaught TypeError: bild is null .

If I run it in a normal html file it work.

CODE:

  var text = document.getElementById("text");
var bild = document.getElementById("bild");
var container = document.getElementById("container");

bild.style["background-image"] = "url('stock-bild-portrait-of-confident-senior-business-woman-standing-in-office-with-her-arms-crossed-mature-female-1156978234.jpg')";
//bild.style.background-image = "url('stock-bild-portrait-of-confident-senior-business-woman-standing-in-office-with-her-arms-crossed-mature-female-1156978234.jpg')";

 //  bild.style["background-image"] =  "url('" +  defaultpic + "')";
 alert (bild.style["background-image"]) ;
 bild.style["background-size"] = "300px";
 bild.style["background-repeat"] = "no-repeat";
 bild.style["background-position"] = "center";
 bild.style["border-radius"] = "50%";
 bild.style["background-clip"] = "border-box";
 bild.style["transition"] = "background-size 0.2s";
 bild.style["transition-timing-function"] = "cubic-bezier(.07,1.41,.82,1.41)";
 bild.style["display"] = "block";
 bild.style["width"] = "100px";
 bild.style["height"] = "100px";

 bild.style["text-decoration"] = "none";
 bild.style["cursor"] = "pointer";
 bild.style["overflow"] = "hidden";
 bild.style["text-indent"] = "100%";
 bild.style["white-space"] = "nowrap";

 container.style["position"] = "relative";
 container.style["font-family"] = "Arial";

 text.style["position"] = "center";
 text.style["bottom"] = "5px";
 text.style["left"] = "1px";
 text.style["color"] = "white";

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

will be

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

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

would also do the job.


document.getElementById('id').style = 'left: 55%; z-index: 999; overflow: hidden; width: 0px; height: 0px; opacity: 0; display: none;';

works for me


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width