Changing element style attribute dynamically using JavaScript - 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?

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

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

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

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

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

Related

Why does a <div> have 0 width? [duplicate]

I'm sure the answer is no, but is it possible to determine the width of an element before it is appended to the DOM?
Once it's appended, I know I can use offsetWidth and offsetHeight.
Thanks
The trick is to show the element (display:block) but also hide it (visibility:hidden) and to set it’s position to absolute so that it doesn’t affect the page flow.
The MooTools Element.Measure class does this, as Oscar mentioned.
The Mootools Element.Measure functionality that Oscar mentioned is awesome. For those that use jQuery, here's a quick plugin that accomplishes the same thing:
$.fn.measure = (fn)->
el = $(this).clone(false)
el.css
visibility: 'hidden'
position: 'absolute'
el.appendTo('body')
result = fn.apply(el)
el.remove()
return result
You can call it like this, making sure to return the value (thanks Sam Fen for pointing that out!):
width = $('.my-class-name').measure( function(){ return this.width() } )
Modified the code a bit. Here is a pure JS solution:
function measure(el, fn) {
var pV = el.style.visibility,
pP = el.style.position;
el.style.visibility = 'hidden';
el.style.position = 'absolute';
document.body.appendChild(el);
var result = fn(el);
el.parentNode.removeChild(el);
el.style.visibility = pV;
el.style.position = pP;
return result;
}
var div = document.createElement('div');
div.innerHTML = "<p>Hello</p><br/>";
alert(div.offsetHeight); // 0
alert(measure(div, function(el){return el.offsetHeight})); // 68
What you can do with MooTools is use the Element.Measure class - meaning, you inject the element to the DOM, but keep it hidden. Now, you can measure the element without actually showing it.
http://mootools.net/docs/more/Element/Element.Measure
It is not possible, at least not accurately, because styling affects these properties, and where it's put determines how it is styled and what rules affect it.
For example placing a <p></p> in the page would by default be the width of the body if appended as a child to it, but if you appeneded it inside for example a <div style="width: 100px;"></div>, then you see how that quickly changes things.
/**
* Get bounding client rect for an element (not exists at current DOM tree)
* #param {!HTMLElement} el
* #return {!Promise<!ClientRect>}
*/
function getElementRect(el) {
return new Promise(resolve => {
const element = el.cloneNode(true);
element.style.visibility = "hidden";
element.style.position = "absolute";
document.body.appendChild(element);
resolve(element.getBoundingClientRect());
element.remove();
});
}
const div = /** #type {!HTMLElement} */ (document.createElement("div"));
div.innerHTML = "<p>Hello</p><br/>";
// Execute
(async () => {
const rect = await getElementRect(div);
console.log(rect.width);
})();
DEMO
A slightly different version of #kashesanders: Add the element to a div and put that div inside the DOM.
function getSizeOfNonDomElement(domElement)
{
// setup
let div = document.createElement("div");
div.style.position = "absolute";
div.style.visibility = "hidden";
div.style.display = "block";
div.appendChild (domElement);
document.body.appendChild (div);
// run
let rect = domElement.getBoundingClientRect ();
// cleanup
document.body.removeChild (div);
div.removeChild (domElement);
return rect;
}
If you want to make it more secure, add a construct to check whether it already has a parent and/or is inside the DOM.

append css inline styles in js button for hover [duplicate]

I've created the following...
var menu = document.createElement('select');
How would I now set CSS attributes e.g width: 100px?
Use element.style:
var element = document.createElement('select');
element.style.width = "100px";
Just set the style:
var menu = document.createElement("select");
menu.style.width = "100px";
Or if you like, you can use jQuery:
$(menu).css("width", "100px");
For most styles do this:
var obj = document.createElement('select');
obj.style.width= "100px";
For styles that have hyphens in the name do this instead:
var obj = document.createElement('select');
obj.style["-webkit-background-size"] = "100px"
That's actually quite simple with vanilla JavaScript:
menu.style.width = "100px";
Just for people who want to do the same thing in 2018
You can assign a CSS custom property to your element (through CSS or JS) and change it:
Assigment through CSS:
element {
--element-width: 300px;
width: var(--element-width, 100%);
}
Assignment through JS
ELEMENT.style.setProperty('--element-width', NEW_VALUE);
Get property value through JS
ELEMENT.style.getPropertyValue('--element-width');
Here useful links:
https://developer.mozilla.org/en-US/docs/Web/CSS/--*
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/getPropertyValue
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/removeProperty
All of the answers tell you correctly how to do what you asked but I would advise using JavaScript to set a class on the element and style it by using CSS. That way you are keeping the correct separation between behaviour and style.
Imagine if you got a designer in to re-style the site... they should be able to work purely in CSS without having to work with your JavaScript.
In prototype I would do:
$(newElement).addClassName('blah')
When debugging, I like to be able to add a bunch of css attributes in one line:
menu.style.cssText = 'width: 100px';
Getting used to this style you can add a bunch of css in one line like so:
menu.style.cssText = 'width: 100px; height: 100px; background: #afafaf';
if you want to add a global property, you can use:
var styleEl = document.createElement('style'), styleSheet;
document.head.appendChild(styleEl);
styleSheet = styleEl.sheet;
styleSheet.insertRule(".modal { position:absolute; bottom:auto; }", 0);
<h1>Silence and Smile</h1>
<input type="button" value="Show Red" onclick="document.getElementById('h1').style.color='Red'"/>
<input type="button" value="Show Green" onclick="document.getElementById('h1').style.color='Green'"/>
This works well with most CSS properties if there are no hyphens in them.
var element = document.createElement('select');
element.style.width = "100px";
For properties with hyphens in them like max-width, you should convert the sausage-case to camelCase
var element = document.createElement('select');
element.style.maxWidth = "100px";
<body>
<h1 id="h1">Silence and Smile</h1><br />
<h3 id="h3">Silence and Smile</h3>
<script type="text/javascript">
document.getElementById("h1").style.color = "Red";
document.getElementById("h1").style.background = "Green";
document.getElementById("h3").style.fontSize = "larger" ;
document.getElementById("h3").style.fontFamily = "Arial";
</script>
</body>

Add CSS to a JavaScript button

On my project I use JS Buttons a lot, I can't find a way to add CSS to them. Can you help?
leftBtn = document.createElement('button');
leftBtn.innerText = "<";
rightBtn = document.createElement('button');
rightBtn.innerText = ">";
fireBtn = document.createElement('button');
fireBtn.innerText = "*";
Using CSS classes to change buttons:
<button class="btn">default button</button>
Class used
You could use this code to add a css class to each button:
leftBtn.className = "leftOne";
rightBtn.className = "rightOne";
fireBtn.className = "fireOne";
Then you can use regular css to style them.
You could add a class to your buttons, and then add any styling in CSS:
leftBtn.className = "class_name"
You probably need to use the className to your Javascript:
EXAMPLE:
leftBtn.className = "name";
Hope this helps :)
you can use for example :
leftBtn.style.color = "blue";
Lear more about in https://developer.mozilla.org/es/docs/Web/API/HTMLElement/style
In general, there are two main ways to do that.
The first one using inline styles, just keep in mind that inline style has the highest precedence in a document.
elt.style.color = '...'
or
elt.setAttribute('style', '...')
More info here
The second is by using the class name. You can simply define a class name and write CSS for this class name.
element.className.add = 'your-class-name'
then
.your-class-name { color: red }
In a second way, you can manage class names by using methods like add, remove, toggle
More info here
Just do something like this
leftBtn.style.marginLeft = '20px'
rightBtn.style.marginLeft = '20px'
I guess it
var leftBtn = document.createElement('button');
leftBtn.innerText = "<";
leftBtn.className = "test_style"; // Set class name
leftBtn.style.color = "#000"; // You can also set style properties inline
...
Here is a playground:
https://jsfiddle.net/u5hojsgb/

How to return a javascript set style property to CSS default

I'm trying to work out how, after changing style properties with javascript, I can revert to the value in the stylesheet (including the units).
In the example below, I'd like the output to read 100px (the value in the CSS), rather than 10px, as getComputedStyle gives.
I'd also keep the dummy div at top:25px, so removing the style property won't work.
The best I have is cloning the node and reading the height and storing in a property (http://jsfiddle.net/daneastwell/zHMvh/4/), but this is not really getting the browser's default css value (especially if this is set in ems).
http://jsfiddle.net/daneastwell/zHMvh/1/
<style>
#elem-container{
position: absolute;
left: 100px;
top: 200px;
height: 100px;
}
</style>
<div id="elem-container">dummy</div>
<div id="output"></div>
<script>
function getTheStyle(){
var elem = document.getElementById("elem-container");
elem.style.left = "10px";
elem.style.top = "25px";
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("left");
document.getElementById("output").innerHTML = theCSSprop;
}
getTheStyle();
</script>
Just clear the inline style you wish to fallback to original stylesheet on.
elem.style.left = null;
The style object has a built-in removeProperty() method, so you could do something like:
elem.style.removeProperty('left');
As far as I know, this will have exactly the same effect as setting the property to null, as abaelter suggested. I just thought it might be worth including for the sake of completeness.
Combining abaelter's answer and http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/ gives us the below function:
var getCssStyle = function(elementId, cssProperty) {
var elem = document.getElementById(elementId);
var inlineCssValue = elem.style[cssProperty];
// If the inline style exists remove it, so we have access to the original CSS
if (inlineCssValue !== "") {
elem.style[cssProperty] = null;
}
var cssValue = "";
// For most browsers
if (document.defaultView && document.defaultView.getComputedStyle) {
cssValue = document.defaultView.getComputedStyle(elem, "").getPropertyValue(cssProperty);
}
// For IE except 5
else if (elem.currentStyle){
cssProperty = cssProperty.replace(/\-(\w)/g, function (strMatch, p1) {
return p1.toUpperCase();
});
cssValue = elem.currentStyle[cssProperty];
}
// Put the inline style back if it had one originally
if (inlineCssValue !== "") {
elem.style[cssProperty] = inlineCssValue;
}
return cssValue;
}
Placing in your example code and testing:
console.log("getCssStyle: " + getCssStyle("elem-container", "left"));
Gives us getCssStyle: 100px allowing you to see the original CSS value. If you just want to revert the value then do as abaelter says and null the CSS value you want to revert.

Overriding !important style

Title pretty much sums it up.
The external style sheet has the following code:
td.EvenRow a {
display: none !important;
}
I have tried using:
element.style.display = "inline";
and
element.style.display = "inline !important";
but neither works. Is it possible to override an !important style using javascript.
This is for a greasemonkey extension, if that makes a difference.
There are a couple of simple one-liners you can use to do this.
Set a "style" attribute on the element:
element.setAttribute('style', 'display:inline !important');
or...
Modify the cssText property of the style object:
element.style.cssText = 'display:inline !important';
Either will do the job.
===
I've written a jQuery plugin called "important" to manipulate !important rules in elements, : http://github.com/premasagar/important
===
Edit:
As shared in the comments, the standard CSSOM interface (the API for JavaScript to interact with CSS) provides the setProperty method:
element.style.setProperty(propertyName, value, priority);
E.g:
document.body.style.setProperty('background-color', 'red', 'important');
element.style has a setProperty method that can take the priority as a third parameter:
element.style.setProperty("display", "inline", "important")
It didn't work in old IEs but it should be fine in current browsers.
I believe the only way to do this it to add the style as a new CSS declaration with the '!important' suffix. The easiest way to do this is to append a new <style> element to the head of document:
function addNewStyle(newStyle) {
var styleElement = document.getElementById('styles_js');
if (!styleElement) {
styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.id = 'styles_js';
document.getElementsByTagName('head')[0].appendChild(styleElement);
}
styleElement.appendChild(document.createTextNode(newStyle));
}
addNewStyle('td.EvenRow a {display:inline !important;}')
The rules added with the above method will (if you use the !important suffix) override other previously set styling. If you're not using the suffix then make sure to take concepts like 'specificity' into account.
Building on #Premasagar's excellent answer; if you don't want to remove all the other inline styles use this
//accepts the hyphenated versions (i.e. not 'cssFloat')
addStyle(element, property, value, important) {
//remove previously defined property
if (element.style.setProperty)
element.style.setProperty(property, '');
else
element.style.setAttribute(property, '');
//insert the new style with all the old rules
element.setAttribute('style', element.style.cssText +
property + ':' + value + ((important) ? ' !important' : '') + ';');
}
Can't use removeProperty() because it wont remove !important rules in Chrome.
Can't use element.style[property] = '' because it only accepts camelCase in FireFox.
If you want to update / add single style in DOM Element style attribute you can use this function:
function setCssTextStyle(el, style, value) {
var result = el.style.cssText.match(new RegExp("(?:[;\\s]|^)(" +
style.replace("-", "\\-") + "\\s*:(.*?)(;|$))")),
idx;
if (result) {
idx = result.index + result[0].indexOf(result[1]);
el.style.cssText = el.style.cssText.substring(0, idx) +
style + ": " + value + ";" +
el.style.cssText.substring(idx + result[1].length);
} else {
el.style.cssText += " " + style + ": " + value + ";";
}
}
style.cssText is supported for all major browsers.
Use case example:
var elem = document.getElementById("elementId");
setCssTextStyle(elem, "margin-top", "10px !important");
Here is link to demo
If all you are doing is adding css to the page, then I would suggest you use the Stylish addon, and write a user style instead of a user script, because a user style is more efficient and appropriate.
See this page with information on how to create a user style
https://developer.mozilla.org/en-US/docs/Web/CSS/initial
use initial property in css3
<p style="color:red!important">
this text is red
<em style="color:initial">
this text is in the initial color (e.g. black)
</em>
this is red again
</p>
https://jsfiddle.net/xk6Ut/256/
One option to override CSS class in JavaScript is using an ID for the style element so that we can update the CSS class
function writeStyles(styleName, cssText) {
var styleElement = document.getElementById(styleName);
if (styleElement) document.getElementsByTagName('head')[0].removeChild(
styleElement);
styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.id = styleName;
styleElement.innerHTML = cssText;
document.getElementsByTagName('head')[0].appendChild(styleElement);
}
..
var cssText = '.testDIV{ height:' + height + 'px !important; }';
writeStyles('styles_js', cssText)
Rather than injecting style, if you inject a class(for eg: 'show') through java script, it will work. But here you need css like below. the added class css rule should be below your original rule.
td.EvenRow a{
display: none !important;
}
td.EvenRow a.show{
display: block !important;
}
There we have another possibility to remove a property value from the CSS.
Like using the replace method in js. But you have to know exactly the ID of the style, or you can write a for loop to detecting that by (count styles on the page, then check if any of those 'includes' or 'match' an !important value. & you can count also - how much contains them, or just simply write a global [regexp: /str/gi] replacing method)
Mine is very simple, but I attach a jsBin, for example:
https://jsbin.com/geqodeg/edit?html,css,js,output
First I set the body background in CSS for yellow !important, then I overrided by JS for darkPink.
Below is a snippet of code to set the important parameter for the style attribute using jquery.
$.fn.setFixedStyle = function(styles){
var s = $(this).attr("style");
s = "{"+s.replace(/;/g,",").replace(/'|"/g,"");
s = s.substring(0,s.length-1)+"}";
s = s.replace(/,/g,"\",\"").replace(/{/g,"{\"").replace(/}/g,"\"}").replace(/:/g,"\":\"");
var stOb = JSON.parse(s),st;
if(!styles){
$.each(stOb,function(k,v){
stOb[k] +=" !important";
});
}
else{
$.each(styles,function(k,v){
if(v.length>0){
stOb[k] = v+" !important";
}else{
stOb[k] += " !important";
}
});
}
var ns = JSON.stringify(stOb);
$(this).attr("style",ns.replace(/"|{|}/g,"").replace(/,/g,";"));
};
Usage is pretty simple.Just pass an object containing all the attributes you want to set as important.
$("#i1").setFixedStyle({"width":"50px","height":""});
There are two additional options.
1.To just add important parameter to already present style attribute pass empty string.
2.To add important param for all attributes present dont pass anything. It will set all attributes as important.
Here is it live in action. http://codepen.io/agaase/pen/nkvjr

Categories

Resources