How to get CSS property value from style tag?

I have the following code on the page (along with other tags), and I want to end up with the numeric value of "z-index" in the 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'm sure this 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 for a better approach?

+4
source share
4 answers

I hope this helps 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 the CSS property without adding an element to the DOM

$('<p/>').css('z-index')
+2
source
  • document.styleSheets stores the object of all stylesheets in a document.
  • cssRules: , , CSSRule,
  • CSSRule cssText, css.

... , jQuery...

+1

, , , ($('.main_style').css('z-index');), document.styleSheets

CSSStyleSheet, . , , , , . , , .

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);
        }
    }
}

jquery-, , :

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

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

jQuery.css()?

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

All Articles