user2078023
user2078023

Reputation: 1266

How do I get a CSS property value from a style tag?

I have the following code in the of the page (along with other tags) and I want eventually to retrieve the numeric value of "z-index" into a variable:

<style>
.main_style {
  font-family:Verdana, Arial, Helvetica, sans-serif;
  font-size:11px;
  color:#CCC;
  text-align:center;
  border:7px solid #333;
  -moz-border-radius:5px /;
  border-radius:5px / 5px;
  background-color:#333;
  z-index:1000;
  width:auto;
  min-width:0;
  max-width:1000px;
  height:auto;
  min-height:0;
  max-height:1000px;
  margin:0;
}
</style>

I thought of the following (with jQuery and Javascript) but I am sure it is not the most efficient way to do this:

var a1=$("style:contains('.main_style')").html();
var a2=+a1.match(/z-index: (\d*?);/i)[1];

Here is its FIDDLE: http://jsfiddle.net/R2S4q/

Any other ideas on what is the best approach?

Upvotes: 4

Views: 183

Answers (4)

fehays
fehays

Reputation: 3167

If you are unable to use a selector like other's have mentioned (e.g. - $('.main_style').css('z-index');), you can use document.styleSheets

This will return an array of CSSStyleSheet objects that you can iterate through. Not sure if this is more efficient and the code is certainly more complex. You may be better off with your solution but here's a fiddle if you want to check it out.

http://jsfiddle.net/fehays/WWxru/1/

var rules = [];
for (var i = 0; i < document.styleSheets.length; i++) {
    var sheet = document.styleSheets[i];
    if (sheet.ownerNode.nodeName == 'STYLE') {
        rules.push(sheet.rules);
    }
}
for (var i = 0; i < rules.length; i++) {
    var rule = rules[i];
    for (var j = 0; j < rule.length; j++) {
        if (rule[j].selectorText == '.main_style') {
            $('#test').html(rule[j].style.zIndex);
        }
    }
}

A simple jquery solution like this would work as well:

$('<span />').addClass('main_style')
    .css('position','relative')
    .hide()
    .appendTo('body');

$('#test').html($('.main_style').css('z-index'));

Upvotes: 1

Ashok Shah
Ashok Shah

Reputation: 956

I hope this should help you

<style>
    p {z-index: 99}
</style>

$(document).ready(function() {
    var $p = $("<p></p>").hide().appendTo("body");
    alert($p.css("z-index"));
    $p.remove();
});

You can even get CSS property without adding element to the DOM

$('<p/>').css('z-index')

Upvotes: 2

Vlas Bashynskyi
Vlas Bashynskyi

Reputation: 2013

  • document.styleSheets holds an object of all stylesheets in the document.
  • each stylesheet object has a cssRules property: A read-only, array-like object holding the CSSRule objects that compose the stylesheet
  • each CSSRule object has a cssText property that is the value of that css rule.

...yeah, better use jQuery...

Upvotes: 1

dguay
dguay

Reputation: 1683

You could use jQuery .css() function?

var z_index = $('.your_class').css('z-index')

Upvotes: 0

Related Questions