Got another basic question that I couldn't seem to find the answer for online. I can change the CSS property of an element easily using javascript,
document.getElementById("ExampleID").style.height="30px";
however whenever I try printing a property to the console, with
console.log(document.getElementById("ExampleID").style.height);
it prints a blank line instead of the property. How can I print a style property value of the desired element? Thank you very much
You can use getComputedStyle
let elem = document.getElementById('test');
let ht = window.getComputedStyle(elem, null).getPropertyValue("height");
console.log(ht)
.test {
height: 300px;
width: 300px;
border: 1px solid red;
}
<div class="test" id="test">Test</div>
Make sure you are testing with an actual element that will be returned from your selection (see example below). Otherwise your code is fine.
const elem = document.getElementById('elemId');
elem.style.height = '30px';
console.log(elem.style.height);
<div id="elemId"></div>
document.getElementById("ExampleID").style.height="30px";
console.log(document.getElementById('ExampleID').clientHeight);
console.log(document.getElementById('ExampleID').offsetHeight);
<div id="ExampleID">
clientHeight includes padding.<br>
offsetHeight includes padding, scrollBar and borders.
</div>
clientHeight includes padding.
offsetHeight includes padding, scrollBar and borders.
You need to check HTML part in this case.
If you are setting from javascript then Your code is working fine.
In case Styles defined in CSS use window.getComputedStyle()
The window.getComputedStyle() method returns an object that reports the values of all CSS properties of an element after applying active stylesheets and resolving any basic computation those values may contain. Individual CSS property values are accessed through APIs provided by the object or by simply indexing with CSS property names.
Here is working snippet:
var divEle=document.getElementById("ExampleID");
console.log("Before:height::"+divEle.style.height);
console.log("Before:color::"+divEle.style.color);
var heightCss = window.getComputedStyle(divEle, null).getPropertyValue("height");
var colorCss = window.getComputedStyle(divEle, null).getPropertyValue("color");
console.log("Before:height from css::"+heightCss)
console.log("Before:color from css::"+colorCss)
function changeCss(){
divEle.style.height="30px";
divEle.style.color="blue";
console.log("After:height::"+divEle.style.height);
console.log("After:color::"+divEle.style.color);
}
.divClass {
height: 40px;
color: red;
width: 40px;
border: 2px solid black;
}
<div class="divClass" id="ExampleID">test</div><div><input type="button" onClick="changeCss();" value="Change Css"/></div>
Related
I am grabbing the element below like:
let box = document.querySelector('.zero');
When I go to check the backgroundColor in javascript, it shows as "" :
box.style.backgroundColor // ""
If I'm grabbing the element node, why doesn't it list the backgroundColor as #DCDCDC, like what I set it in my CSS as? I assume it's due to the multiple classes on the element but not sure why.
code:
<div class="tic-tac-box zero">
</div>
.tic-tac-box {
background-color: #DCDCDC;
border-radius: 5px;
border: 2px solid white;
}
The reason it's not logging the color is not because there are multiple classes, but because how the DOM API works, and that Javascript doesn't know what's going on with your linked CSS. If you want to log the current style of your element you'll have to use the getComputedStyle() method:
getComputedStyle(box).backgroundColor); // rgb(220, 220, 220)
tldr: "The style property only retrieves inlined CSS values while getComputedStyle style retrieves computed CSS values." Check out this article for more info. You'll notice when you set colors with that syntax, it appends inline styles too.
When working with calc()ulated properties in CSS, is it possible to access their expanded (i.e., actually calculated) values through Javacsript?
For instance, consider the following CSS:
:root {
--ratio: calc(16 / 9);
--width: 100px;
--height: calc(var(--width) / var(--ratio));
}
And Javascript:
const computedStyle = window.getComputedStyle(document.documentElement);
console.info(computedStyle.getPropertyValue('--height'));
One would expect to see 56px being printed; instead, the string "calc(var(--width) / var(--ratio))" is returned.
Even if you try applying it to some CSS class property and reading from the class declaration instead, it won't work:
.rectangle {
height: var(--height);
}
Javascript:
const rectangleClassDeclaration = /* find it through document.styleSheets */
console.info(rectangleClassDeclaration.style.getPropertyValue('height'));
And the console shows "var(--height)".
So, is there a way to access the final, calculated value through Javascript?
One hack that I could think of is applying the value to some DOM element and them reading from it instead.
CSS:
.rectangle {
height: var(--height);
}
HTML:
<div class="rectangle"></div>
Javascript:
const rectangle = document.querySelector('.rectangle');
const computedStyle = window.getComputedStyle(rectangle);
console.info(computedStyle.getPropertyValue('height'));
And then you would see 56px as the result. But this is kinda hacky, so it would be good to find out some way of accessing the variable's computed value directly. It works, anyway.
See my CodePen with working code.
It was my understanding that [some elem].style.maginTop would return a string with the element's top margin.
Instead, I'm always getting a blank string. I want to use this with the body, but I also tried on a div, and that didn't work either.
console.log(document.body.style.marginTop); // logs ""
console.log(typeof(document.body.style.marginTop)); // logs "String"
var elem = document.getElementById("testDiv");
console.log(elem.style.marginTop); // logs ""
body {
margin-top:100px;
}
#testDiv {
margin-top:50px;
}
hi!
<div id="testDiv">test</div>
I'm not sure what I'm doing wrong... Does anybody have a non-jQuery solution to this?
The HTMLElement.style only returns inline styles:
The HTMLElement.style property returns a CSSStyleDeclaration object that represents the element's style attribute.
To access the styles from stylesheets use Window.getComputedStyle(element):
The Window.getComputedStyle() method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.
var elem = document.getElementById("testDiv");
var style = window.getComputedStyle(elem);
//output
document.body.innerHTML = style.marginTop;
body {
margin-top:100px;
}
#testDiv {
margin-top:50px;
}
hi!
<div id="testDiv">test</div>
You can use getComputedStyle and getPropertyValue to get top margin.
console.log(document.body.style.marginTop); // logs ""
console.log(typeof(document.body.style.marginTop)); // logs "String"
var elem = document.getElementById("testDiv");
//console.log(elem.style.marginTop); // logs ""
console.log(getComputedStyle(elem).getPropertyValue("margin-top"));
alert(getComputedStyle(elem).getPropertyValue("margin-top"));
body {
margin-top:100px;
}
#testDiv {
margin-top:50px;
}
hi!
<div id="testDiv">test</div>
Tested and working.
I don't know why, but I got it working by implicitly assigning the margin-top by JS first. I know why my answer works (it's been over 2 years so I better know why). By setting the values of div#test and body to 50px and
100px like this:
document.getElementById("testDiv").style.marginTop = '50px';
document.body.style.marginTop = '100px';
I'm actually setting the CSS property/value of the elements inline:
<body style='margin-top: 100px'>
<div id='testDiv' style='margin-top: 50px'>test</div>
</body>
Whenever the .style property is used, the CSS property/value that follows it is always inline. One important thing to remember about inline CSS styles is that they have a higher priority than the other 2 means of CSS Declaration: external stylesheets (ex. <link href="file.css"...) and inline stylesheet (ex. <style>...</style>). The only way to override an inline style is to use !important (unless of course the inline style has !important as well.)
So if the.style property is used to read a property/value of an element, it'll only return the inline style value if it actually exists which in OP's case it never did and in my case it did because I used .style to assign the property/values. While my solution is correct, the answers by Nicolo and Mr. Karlsson are better since you'll get the values from all CSS stylesheets.
document.getElementById("testDiv").style.marginTop = '50px';
document.body.style.marginTop = '100px';
console.log(document.getElementById("testDiv").style.marginTop);
console.log(document.body.style.marginTop);
body {
margin-top: 100px;
}
#testDiv {
margin-top: 50px;
}
hi!
<div id="testDiv">test</div>
Hm, I tried it as well with the same result as you did. A quick google search turned up Using JavaScript to read html / body tag margin-top which uses style.getPropertyValue() to return the information you're looking for.
instead of using core javascript, let you use js library jQuery. Then use this syntaxt to get its value.:
console.log($('body').css('margin-top'));
for pure javascript use this
var element = document.body,
style = window.getComputedStyle(element),
margin_top = style.getPropertyValue('margin-top');
console.log(margin_top);
http://jsfiddle.net/hAw53/726/
I've tried this in IE9 only, and I'm receiving just an empty string back - no border width. What is wrong?!
<!DOCTYPE html><html><head>
<style type="text/css">
.myCanvas {
border-width: 2px;
border-style: solid;
border-color: red;
}
</style>
</head><body>
<div class="myCanvas">Something here</div>
<script type="text/javascript">
(function(){
var borderWidth = document.getElementsByTagName('div')[0].style.borderWidth;
console.log(borderWidth);
})();
</script>
</body>html>
The style object only contains data stored in the element's HTML style attribute. Here the element has no style attribute, let alone a border-width declaration within. This would only work if your markup looked like this:
<div class="myCanvas" style="border-width:2px">Something here</div>
2px
To pull computed CSS styles, you need to use window.getComputedStyle():
var div = document.getElementsByTagName('div')[0],
borderWidth = window.getComputedStyle(div).borderWidth;
console.log(borderWidth);
2px
JSFiddle demo.
Unfortunately this will not work on IE8, but will work on all other modern browsers. (Browser Support)
element.style only refers to the element's style attribute. From MDN:
To get the values of all CSS properties for an element you should use window.getComputedStyle() instead.
This question already has answers here:
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
(26 answers)
Closed 3 years ago.
This is what my code looks like:
$('.mainSpan:before').css('background','url(_gfx/cmn/main_bg.png)');
This does not seem to work so I'm asking if it's even possible to add
background images to shadow elements with jQuery.
It's not possible to directly access pseudo-elements with Javascript as they're not part of the DOM. You can read their style using the optional second argument - which most, although not all, browsers in current use support - in .getComputedStyle() but you can't directly change their style.
However, you could change their style indirectly by adding in a new style element containing new rules. For example:
http://jsfiddle.net/sjFML/
The initial CSS assigns the :before pseudo-element with a green background, which is turned to black by inserting a new style element.
HTML:
<div id="theDiv"></div>
CSS:
#theDiv {
height: 100px;
background: red;
}
#theDiv:before {
content:' ';
display: block;
width: 50px;
height: 50px;
background: green;
}
Javascript:
var styleElem = document.head.appendChild(document.createElement("style"));
styleElem.innerHTML = "#theDiv:before {background: black;}";
There is also solution with CSS Variables (aka custom properties):
var style = document.querySelector('.foo').style;
style.setProperty('--background', 'url(http://placekitten.com/200/300)');
.foo::before {
background: var(--background);
content: '';
display: block;
width: 200px;
height: 300px;
}
<div class="foo"></div>
For browser support see Can I use and here is link to Ponyfill (same as Polyfill, but you need to call a function)
Ponyfill work with CSS in link and style CSS, but if you use code below, you can set the variable like with setProperty (it will run only in browsers that don't support CSS Variables like IE11)
var style = document.querySelector('.foo').style;
style.setProperty('--background', 'url(http://placekitten.com/200/300)');
cssVars({
variables: {'--background': 'url(http://placekitten.com/200/300)'}
});
.foo::before {
background: var(--background);
content: '';
display: block;
width: 200px;
height: 300px;
}
<div class="foo"></div>
<script src="https://unpkg.com/css-vars-ponyfill#2/dist/css-vars-ponyfill.min.js"></script>
Unfortunately the cssVar ponyfill is global like setting var on :root. If you need to support IE11 or other old browser you can try to search for better polyfill or library.
It is possible to change the value of the ::after element but not directly. Gotta be sneaky. Works on all browsers.
Let's say you have an element:
<div class="thing1">hi here</class>
And you got an ::after css style for it:
.thing1::after {
content:"I am what comes ::after a thing :)";
display: inline-block;
background-color: #4455ff;
padding:3px;
border: 1px solid #000000; }
And you want to change the content and the background color of the ::after pseudo-element using javascript. To do this, make a second CSS rule with the changes you want applied and have both the current class name and add a totally new class name to it. So let's say I want to change the content and the background color a bit and leave the rest of the stuff, the same:
.thing1.extra_stuff::after {
content:"Some parts of me, changed!";
background-color: #8888cc; }
Now, you can just fire off an onclick javascript event that will apply those two new rules to the element, by adding the second class name, to the element :) yay
function change_the_after_attribute(thing_button) {
thing_button.className="thing1 extra_stuff"; }
https://jsfiddle.net/bt8n26a5/
fun side notes:
You can use thing_button.classList.add("extra_stuff"); and thing_button.classList.remove("extra_stuff"); to make the function applicable to many different elements with many different class names, and to be able to remove your changes, as well!
Use a variable instead of the "extra_stuff" string to change what you're adding more dynamically.