4

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>
Jens Törnell
  • 23,180
  • 45
  • 124
  • 206

4 Answers4

4

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.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Would this also work in older browsers where jQuery uses the sizzle engine? Because it could be possible that they are not implementing the spec as closely as a modern browser's internal query selector. – Esailija Nov 18 '11 at 21:29
  • It's part of the CSS spec and has been for a long time so it should work, but my recommendation is for the OP to remove the colons from the ID values. You'd have to test a particular Sizzle version if you want to know for sure if this works there, but it should. – jfriend00 Nov 18 '11 at 21:35
  • That worked, thanks!. I did not add the colon myself, it's generated by the LESS language (http://lesscss.org/). – Jens Törnell Nov 18 '11 at 21:46
3

Try:

$('#less:concepts-less-css-style')[0].innerHTML
Mondo
  • 327
  • 1
  • 5
3

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.

Esailija
  • 138,174
  • 23
  • 272
  • 326
0

Use a attribute-selector instead

  var test = $('style[id="'+my_id+'"]').text();
    //or
  var test2 = $('style[id="less:concepts-less-css-style"]').html();
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201