Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get style tag content with jQuery?

Tags:

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>
like image 648
Jens Törnell Avatar asked Dec 28 '22 10:12

Jens Törnell


2 Answers

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.

like image 105
jfriend00 Avatar answered Jan 11 '23 20:01

jfriend00


Try:

$('#less:concepts-less-css-style')[0].innerHTML
like image 36
Mondo Avatar answered Jan 11 '23 20:01

Mondo