Changing element style attribute dynamically using JavaScript
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...
How to dynamically create CSS class in JavaScript and apply?
Here is an option:
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.cssClass { color: #f00; }';
document.getElementsByTagName('head')[0].appendChild(style);
document.getElementById('someElementId').className = 'cssClass';
<div id="someElementId">test text</div>
How to dynamically change CSS style attribute of DIV tag?
var div = document.getElementById('div1');
// Clear Value
div.setAttribute('style','');
// OR
div.removeAttribute('style');
// Set Style / Append Style
div.style.backgroundColor = '#ff0000';
Don't modify the style attribute directly when adding or changing styles unless you want to remove them all.JavaScript removeAttribute: https://developer.mozilla.org/en-US/docs/Web/API/Element.removeAttribute
Javascript Style: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.style
Apply CSS dynamically with JavaScript
Using Jquery
Use the css() function to apply style to existing elements where you pass an object containing styles :
var styles = {
backgroundColor : "#ddd",
fontWeight: ""
};
$("#myId").css(styles);
You can also apply one style at the time with :$("#myId").css("border-color", "#FFFFFF");
Vanilla JS :var myDiv = document.getElementById("#myId");
myDiv.setAttribute("style", "border-color:#FFFFFF;");
With Css :You can also use a separate css file containing the different styles needed inside classes, and depending on the context you add or remove those classes to your elements.
in your css file you can have classes like
.myClass {
background-color: red;
}
.myOtherClass {
background-color: blue;
}
Again using jquery, to add or remove a class to an element, you can use$("#myDiv").addClass('myClass');
or$("#myDiv").removeClass('myClass');
Again, you can also do the same with vanilla JS:document.getElementById("#myId").classList.add('myClass')
ordocument.getElementById("#myId").classList.remove('myClass')
I think this is a cleaner way as it separates your style from your logic. But if the values of your css depends from what is returned by the server, this solution might be difficult to apply. Cannot apply style to dynamically created elements in javascript
Problem
The default value of the property position of a div is static. When you try to set left/right [..] on static element it has no effect on that element.static : every element has a static position by default, so the
element will stick to the normal page flow. So if there is a
left/right/top/bottom/z-index set then there will be no effect on that
element. relative : an element's original position remains in the flow
of the document, just like the static value.
Solution
- You have to set the position property in your created element to
absolute
,fixed
orrelative
.
let dynel = document.createElement('div');
dynel.className = 'foo';
dynel.style.position = "absolute"
dynel.style.width = '5px';
dynel.style.height = '5px';
dynel.style.backgroundColor = 'blue';
document.body.appendChild(dynel);
var foo = document.getElementsByClassName('foo');
foo[0].style.top = '50px';
foo[0].style.left = '200px';
How to Change the Fixed Position Styles Dynamically - using JavaScript. Set position name, Values
You can change the style using square brackets:
dynamic_btn.style[position_1] = position_1_value;
This way, you can access values of dynamically named properties. Styling elements that are dynamically generated
You can add the class the element using classList.add()
.
Demo:
var result = [1,2];
var menuMgtCategoryButtons = document.getElementById('menuMgtCategoryButtons');
for(var i = 0; i < result.length;i++){
var menuCatButton = document.createElement("button");
menuCatButton.id = "menu-mgt-button-"+result[i];
menuCatButton.textContent = "Button "+result[i]; // add the text to the button
menuCatButton.classList.add('new-button'); // add the class to the button
menuMgtCategoryButtons.appendChild(menuCatButton);
}
.new-button {
background-color: #4CAF50;
border: 1px solid;
color: white;
text-decoration: none;
display: inline-block;
font-size: 15px;
margin: 4px 20px;
cursor: pointer;
width: 120px;
height:50px;
white-space: normal;
}
.new-button:hover {
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);
}
<div id="menuMgtCategoryButtons"></div>
How to dynamically change the style tag using JavaScript?
You are probably trying to add css to the style tag. This can be accomplished using:
document.getElementsByTagName('style')[0].innerHTML=""; //some css goes here
You can also use:document.styleSheets[0].cssText = ""; //some css goes here
Related Topics
Write Elements into a Child Iframe Using JavaScript or Jquery
Unchecked Runtime.Lasterror While Running Tabs.Executescript
Why Is 'This' Undefined Inside Class Method When Using Promises
How to Test for Nan in JavaScript
Mocking a Useragent in JavaScript
Cancel/Kill Window.Settimeout() Before It Happens
Detect If an Element Is Visible with Jquery
Prevent JavaScript Keydown Event from Being Handled Multiple Times While Held Down
How to Change the Pop-Up Position of the Jquery Datepicker Control
What's the API Key for in Google Maps API V3
How to Get Month and Date of JavaScript in 2 Digit Format
Understanding JavaScript Promise Object
Parse String to Date with Moment.Js
Domnodeinserted Equivalent in Ie