Jens Törnell
Jens Törnell

Reputation: 24768

Get style tag content with jQuery?

The problem

I'm trying to get the content within the style tags but I can't get it to work.

What the code does

I use jQuery and try to get the style content with text() and html(). It does not work.

My code

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet/less" type="text/css" href="css/style.less">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>

    <style id="less:concepts-less-css-style" media="screen" type="text/css">
        body {
            padding: 10px;
            background: blue;
        }
    </style>

</head>
<body>
<script src="js/less-1.1.5.min.js" type="text/javascript"></script>
<script type="text/javascript">
        jQuery(document).ready(function($) {        
            var my_id = $('style').attr('id');
            var test = $('#less:concepts-less-css-style').text();
            var test2 = $('#less:concepts-less-css-style').html();
            alert(test + "#" + test2 + "#" + my_id);
        });
    </script>
</body>
</html>

Upvotes: 4

Views: 13939

Answers (4)

Dr.Molle
Dr.Molle

Reputation: 117334

Use a attribute-selector instead

  var test = $('style[id="'+my_id+'"]').text();
    //or
  var test2 = $('style[id="less:concepts-less-css-style"]').html();

Upvotes: 0

jfriend00
jfriend00

Reputation: 707376

I think you have to escape the colon character in your ID because it would normally mean something in the selector syntax. See Handling a colon in an element ID in a CSS selector for a discussion of this issue.

$('#less\\:concepts-less-css-style')

I personally avoid special characters with CSS selector meaning in my ID or class values to avoid this complication.

Upvotes: 4

Esailija
Esailija

Reputation: 140230

The id is so that jQuery thinks it's a pseudo selector.. try

var elm = document.getElementById("less:concepts-less-css-style"),
    content = elm.innerHTML || elm.innerText || elm.textContent;

    alert( content );

You could of course change the id not to be so erratic and jQuery will work.

Upvotes: 3

Mondo
Mondo

Reputation: 327

Try:

$('#less:concepts-less-css-style')[0].innerHTML

Upvotes: 3

Related Questions