I am wondering if there is a way to get css value from stylesheet file when there is no element in the DOM using it? I am using jQuery and I use selector $(".classname").css() to get the values. But with the case "classname" is not in any element, what to do to get the value" Thanks
Just create an element with that class name and inspect it. You don't even need to attach it to the DOM:
var $el = $('<div class="classname"></div>');
var opacity = $el.css('opacity') // or whatever
Even though $el
is not actually present in the DOM, you still get access to all of its style properties.
Edit: as mentioned in the comments, this approach does not always work as expected (eg inherited css values not defined on .classname explicitly, selector specificity above .classname, etc).
For example the following fails due to #foo
increasing the selector specificity beyond that of a standalone .bar
:
css:
#foo .bar { color: red; }
js:
var $el = $('<div class="bar"></div>');
$el.css('color'); // Expected: "red", Actual: ""
You could go (this also works in chrome):
var $elem = $('<div id="foo"></div>').appendTo('body'),
value = $elem.css('margin-top');
$('#foo').remove();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With