Gary Willoughby
Gary Willoughby

Reputation: 52588

Jquery problem getting text from a script tag?

I have this small HTML document:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
    <head>
        <title>HTML Test</title>

        <script type="text/javascript" src="jquery-1.3.2.min.js"></script>

        <script type="text/javascript">
            $(document).ready(function()
            {
                $("script").each(function()
                {
                    if($(this).attr("type") == "code")
                    {
                        alert($(this).text());
                    }

                });
            });
        </script>

    </head>

    <body>

<script type="code">
var Text = "Text";
</script>

    </body>
</html>

When run using Firefox the alert displays the text contents of the <script type="code"> tag. When run in IE8 it displays nothing.

Do you know why? I'm stumped.

Upvotes: 4

Views: 7809

Answers (3)

AmbrosiaDevelopments
AmbrosiaDevelopments

Reputation: 2592

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
    <head>
        <title>HTML Test</title>
        <script type="text/javascript" src="jquery-1.3.2.min.js"></script
        <script type="text/javascript">
            $(document).ready(function()
            {
                    $("script").each(function()
                    {
                            if($(this).attr("type") == "code")
                            {
                                alert($(this).html());
                            }
                    });
            });
        </script>
    </head>
    <body>
        <script type="code">
            var Text = "Text";
        </script>
    </body>
</html>

Upvotes: 1

Darko
Darko

Reputation: 38880

You might have more luck with .html() and if that doesn't work try this.innerHtml. I did not test this however.

I do have another tip for your code however. If you want only scripts of type code you can have a single selector instead of having to check the attribute in the loop:

$("script[type=code]").each(function() {
    alert($(this).html());
    alert(this.innerHtml);
});

Upvotes: 9

CodeJoust
CodeJoust

Reputation: 3800

Use .html() instead for better support with ie.

You can also look at: http://docs.jquery.com/Plugins/Metadata for storing information in script tags.

Upvotes: 2

Related Questions