This question already has answers here:
Get a CSS value from external style sheet with Javascript/jQuery
(5 answers)
Closed 9 years ago.
I am trying to access css property like this:
.box {
position: absolute;
background-color: red;
height: 10px;
width: 10px;
}
JS:
var height = $('.box').css('height');
I know, the above code is wrong and this actually doesn't work as .box is not available in the DOM.
Another thing that i tried:
var height = $("<span class='box'></span>").css('height');
My question is: how can I get the height of .box without having any element in the DOM with class box ?
On a modern browser you could use document.stylesheets, and the stylesheet would need to be in the original HTML and the source needs to match the Same Origin Policy, i.e. you can't inject the stylesheet from say a Chrome extension as it does not show in document.stylesheets
CSS
.box {
position:absolute;
background-color:red;
height:10px;
width:10px;
}
Javascript
function propertyFromStylesheet(selector, attribute) {
var value;
[].some.call(document.styleSheets, function (sheet) {
return [].some.call(sheet.rules, function (rule) {
if (selector === rule.selectorText) {
return [].some.call(rule.style, function (style) {
if (attribute === style) {
value = rule.style.getPropertyValue(attribute);
return true;
}
return false;
});
}
return false;
});
});
return value;
}
console.log(propertyFromStylesheet(".box", "height"));
Output
10px
On jsfiddle
The only way you can get then without using a DOM element is by downloading the stylesheet and parsing the contents. You can also access the compiled stylesheet by going to document.stylesheets and finding the rule. You can also use window.getComputedStyle(element) and create an element such as document.createElement('div') and attach the '.box' className to it.
Keep in mind that doing any of this implies that the stylesheet is on the same domain and port of where your html file is.
To get the computed height of an element as set in a stylesheet, it has to exists in the DOM. You solve this by creating an element, positioning it way off the visible screen, and appending it to the body (or anywhere really).
To get the height you can use .height(), or .innerHeight() to get the height without margins and borders, but including padding :
var elem = $('<span />', {'class':'box',
style:'position:fixed;top:-9999px'}).appendTo('body');
var height = elem.innerHeight();
elem.remove();
FIDDLE
There's usually no need to access and parse the stylesheet for this, except in really special cases, where you're not looking for something like an elements height, but for instance trying to check if some special style is set in a specific stylesheet etc.
Related
What is currently the best and easiest way to change CSS style using javascript?
I have several elements on the page with class="colorManipul" and in css .colorManipul{filter: grayscale(33%);}
I want to change the value directly in CSS so that it is reflected on all required elements with this class
Thanks for the advice, link, example, ... just anything
You can change the value of a CSS property with JS. To easily target a property you should target a CSS-Variable:
window.addEventListener('DOMContentLoaded', function() {
document.documentElement.style.setProperty('--body-bg', 'blue');
})
:root {
--body-bg: red;
}
body {
background: var(--body-bg);
}
However, this is harder to debug and a cleaner solution is to simply add a class to all elements with a certain class.
document.querySelectorAll('.colorManipul').forEach(el =>
el.classList.add('class-name')
);
If you want to change percentage of grayscale value, you can use css variable and change its value from JS For example:
CSS:
:root {
--grayscale: 33%;
}
.colorManipul {
filter: grayscale(var(--grayscale));
}
JS:
const grayscaleValue = 50;
root.style.setProperty('--grayscale', `${grayscaleValue}%`);
Should I put the scoped CSS in my master file, or should I change the print function in order to accomodate components' scoped CSS? In the second case, how should I change the JS function?
I use Laravel 5 with many Vue Components. In one of them, I have the following scoped CSS
<style scoped>
td.not-purchased{
background-color: darkgrey;
}
td.not-assigned-here{
background-color: lightgreen;
}
td .checkbox{
margin-top: 0;
margin-bottom: 0;
display: inline-block;
}
table th:nth-child(n+3),
table td:nth-child(n+3){
width: 50px;
overflow-x: hidden;
text-overflow: ellipsis;
}
</style>
When printing the generated content, the function opens the content in a new page and copies the external CSS in the HEAD of the original document.
$(document).on('click', '.glyphicon[data-printselector]', function(){
if($(this).data('printselector') != ''){
// Print in new window
let printHtml = $($(this).data('printselector')).clone(),
printWindow = window.open(),
waitTimeout;
$(printWindow.document.body).append($('<div />', {class: 'container'}).append(printHtml));
$.each($('link'), function() {
$(printWindow.document.head).append($(this).clone());
clearTimeout(waitTimeout);
waitTimeout = setTimeout(function(){
// Here we ensure that CSS is loaded properly
printWindow.print();
printWindow.close();
}, window.changeFunctionTimeoutLong);
});
}
else
window.print();
});
I know this could be done by putting the scoped CSS directly into the master CSS of my website, but I believe this goes against the whole point of having scoped CSS.
The way Vue works by default, your scoped CSS is transformed in the following way:
The CSS selectors in your CSS get an additional attribute selector, and the CSS itself is inlined in a <style> tag into your page
The HTML elements matching the selectors in your CSS are given the corresponding unique attribute
That way, the CSS rules are scoped to the specific HTML elements that match the unique attributes.
If you want your scoped styles to work in a different context than the original page, there's two things you need to make sure work:
The HTML elements have the necessary attributes
The <style> tag with the CSS with those attributes is present
From your description, it sounds like the latter at least is missing. A quick thing to try this out would be to also copy all <style> tags from your page when you're copying the external CSS, and see if that works.
Then you can determine whether that's good enough for you, or whether you actually want to see about just grabbing the styles you need (in case you have a lot of styles).
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 have a web application that utilizes a separate print stylesheet to control how the page looks when it comes out of the printer. That was working wonderfully until I recently made some Javascript enhancements to the site. One of these enhancements allows the user to freeze the page header and navigation, as well as table headers. The Javascript behind this does some CSS trickery to freeze the elements on the screen. Unfortunately, applying position: fixed to my header (for example) causes it to print on every page, and this is not a desired effect. How can I use Javascript to tweak element styles on the client-side without affecting the print style?
#media print { #foo { color: blue; } } /* Print definition */
#media screen { #foo { color: green; } } /* Display definition */
document.getElementById('foo').style.color = 'red'; /* Overrides both! */
Instead of changing properties on your elements with this:
document.getElementById('foo').style.color = 'red';
append a new <style> element, for example:
$('<style>#media screen { #foo { color: green; } }</style>').appendTo('head');
It would be better to concatenate all your required changes into one <style> element, if possible.
Add !important to your print rules.
You can try this
#media print { #foo { color: blue !important; } }
The problem is that javascript .style.something, edits the inline css of the element, therefore it will override the normal css class/id rules.
Or you can, work with classes.
document.getElementById('foo').className = 'redText';
and keep the .redText in your regular css file (not the print one), much much better than filling your print css with !important rules.
No good solution! What I ended up doing is utilizing the onbeforeprint and onafterprint functions in IE (I am in the position here that we only have IE users) to "unfreeze" and "refreeze" the elements...
window.onbeforeprint = function() {
document.getElementById('foo').style.position = 'static';
}
window.onload = window.onafterprint = function() {
var el = document.getElementById('foo');
// Get element position and size
// Set left/top/width/height properties
// Set position to fixed
el.style.position = 'fixed';
}
The proper solution is not to poke styles onto nodes, but to instead tie your screen-specific style tweaks to css classes that only affect your screen rendition of things:
#media screen { .freeze { position: fixed; } } /* Display-only definition */
+
document.getElementById('foo').className = "freeze";
As a bonus, this also makes it easy to change tons of styles with just one line of js, which makes things faster and easier to maintain, too.
This question already has answers here:
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
(26 answers)
How to update placeholder color using Javascript?
(5 answers)
Closed 2 years ago.
Is it possible to change a CSS pseudo-element style via JavaScript?
For example, I want to dynamically set the color of the scrollbar like so:
document.querySelector("#editor::-webkit-scrollbar-thumb:vertical").style.background = localStorage.getItem("Color");
and I also want to be able to tell the scrollbar to hide like so:
document.querySelector("#editor::-webkit-scrollbar").style.visibility = "hidden";
Both of these scripts, however, return:
Uncaught TypeError: Cannot read property 'style' of null
Is there some other way of going about this?
Cross-browser interoperability is not important, I just need it to work in webkit browsers.
If you're comfortable with some graceful degradation in older browsers you can use CSS Vars. Definitely the easiest of the methods I've seen here and elsewhere.
So in your CSS you can write:
#editor {
--scrollbar-background: #ccc;
}
#editor::-webkit-scrollbar-thumb:vertical {
/* Fallback */
background-color: #ccc;
/* Dynamic value */
background-color: var(--scrollbar-background);
}
Then in your JS you can manipulate that value on the #editor element:
document.getElementById("#editor").style.setProperty('--scrollbar-background', localStorage.getItem("Color"));
Lots of other examples of manipulating CSS vars with JS here: https://eager.io/blog/communicating-between-javascript-and-css-with-css-variables/
To edit an existing one which you don't have a direct reference to requires iterating all style sheets on the page and then iterating all rules in each and then string matching the selector.
Here's a reference to a method I posted for adding new CSS for pseudo-elements, the easy version where you're setting from js
Javascript set CSS :after styles
var addRule = (function (style) {
var sheet = document.head.appendChild(style).sheet;
return function (selector, css) {
var propText = typeof css === "string" ? css : Object.keys(css).map(function (p) {
return p + ":" + (p === "content" ? "'" + css[p] + "'" : css[p]);
}).join(";");
sheet.insertRule(selector + "{" + propText + "}", sheet.cssRules.length);
};
})(document.createElement("style"));
addRule("p:before", {
display: "block",
width: "100px",
height: "100px",
background: "red",
"border-radius": "50%",
content: "''"
});
sheet.insertRule returns the index of the new rule which you can use to get a reference to it for it which can be used later to edit it.
EDIT: There is technically a way of directly changing CSS pseudo-element styles via JavaScript, as this answer describes, but the method provided here is preferable.
The closest to changing the style of a pseudo-element in JavaScript is adding and removing classes, then using the pseudo-element with those classes. An example to hide the scrollbar:
CSS
.hidden-scrollbar::-webkit-scrollbar {
visibility: hidden;
}
JavaScript
document.getElementById("editor").classList.add('hidden-scrollbar');
To later remove the same class, you could use:
document.getElementById("editor").classList.remove('hidden-scrollbar');
I changed the background of the ::selection pseudo-element by using CSS custom properties doing the following:
/*CSS Part*/
:root {
--selection-background: #000000;
}
#editor::selection {
background: var(--selection-background);
}
//JavaScript Part
document.documentElement.style.setProperty("--selection-background", "#A4CDFF");
You can't apply styles to psuedo-elements in JavaScript.
You can, however, append a <style> tag to the head of your document (or have a placeholding <style id='mystyles'> and change its content), which adjusts the styles. (This would work better than loading in another stylesheet, because embedded <style> tags have higher precedence than <link>'d ones, making sure you don't get cascading problems.
Alternatively, you could use different class names and have them defined with different psuedo-element styles in the original stylesheet.
I posted a question similar to, but not completely like, this question.
I found a way to retrieve and change styles for pseudo elements and asked what people thought of the method.
My question is at Retrieving or changing css rules for pseudo elements
Basically, you can get a style via a statement such as:
document.styleSheets[0].cssRules[0].style.backgroundColor
And change one with:
document.styleSheets[0].cssRules[0].style.backgroundColor = newColor;
You, of course, have to change the stylesheet and cssRules index. Read my question and the comments it drew.
I've found this works for pseudo elements as well as "regular" element/styles.
An old question, but one I came across when try to dynamically change the colour of the content of an element's :before selector.
The simplest solution I can think of is to use CSS variables, a solution not applicable when the question was asked:
"#editor::-webkit-scrollbar-thumb:vertical {
background: --editorScrollbarClr
}
Change the value in JavaScript:
document.body.style.setProperty(
'--editorScrollbarClr',
localStorage.getItem("Color")
);
The same can be done for other properties.
Looks like querySelector won't work with pseudo-classes/pseudo-elements, at least not those. The only thing I can think of is to dynamically add a stylesheet (or change an existing one) to do what you need.
Lots of good examples here:
How do I load css rules dynamically in Webkit (Safari/Chrome)?