HP.
HP.

Reputation: 19896

Get css value without DOM element

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

Upvotes: 15

Views: 6949

Answers (5)

Jonathan Fingland
Jonathan Fingland

Reputation: 57157

See http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript which presents a cross-browser approach to getting and adding css dynamically.

It works with document.styleSheets and both IE's .rules and everyone else's .cssRules

It also has the advantage of being somewhat abstracted so you don't need to worry about the details.


The above link no longer works. The following is a screenshot of the blog-article, captured by the internet archive wayback in 2008.

enter image description here

The function basically iterates over all styles of all stylesheets and provides the ability to modify / delete them.
Please note that this cannot be recommended, since most modern stylesheets are too large to make this an efficient operation.

Upvotes: 5

mrbackman
mrbackman

Reputation: 51

You could go (this also works in chrome):

var $elem = $('<div id="foo"></div>').appendTo('body'),
    value = $elem.css('margin-top');

$('#foo').remove();

Upvotes: 2

codenamezero
codenamezero

Reputation: 3079

To workaround the Chromium problem, you need to add it to the body:

Sample CSS:

.dummy {
  min-width: 50px;
  max-width: 250px;
}

Sample Javascript:

$(document).ready(function() {
  var dummy = $('<div class="dummy" style="display: none;"></div>').appendTo('body');
  console.log(dummy.css("min-width"));
  console.log(dummy.css("max-width"));
  dummy.remove();
});

This works on all modern browsers, Chrome, FF, IE11.

Upvotes: 0

Crescent Fresh
Crescent Fresh

Reputation: 116980

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

Upvotes: 15

Ionuț G. Stan
Ionuț G. Stan

Reputation: 179098

You have to parse the styles from document.styleSheets.

Upvotes: 0

Related Questions