jquery selector problem with script tags

Posted by Tauren on Stack Overflow See other posts from Stack Overflow or by Tauren
Published on 2010-05-07T09:40:22Z Indexed on 2010/05/07 9:58 UTC
Read the original article Hit count: 484

Filed under:

I'm attempting to select all <script type="text/html"> tags in a page. I use <script> tags to store HTML templates, similar to how John Resig does it. For some reason, the following jquery selector doesn't seem to be selecting anything:

$("script[type*=html]").each(function() {
    alert("Found script "+this.id);
});

This markup is in the BODY of the HTML document:

<body>
    <script id="filter-search" type="text/html">
        <dt>Search</dt>
        <dd><input type="text"/></dd>
    </script>
</body>

I've also tried putting it into the HEAD of the HTML document, and it is still not found. No alert is ever shown.

If I instead change my code to this:

$("script[type*=javascript]").each(function() {
    alert("Found script "+this.id);
});

Then it finds only the scripts in the HEAD that have a src to an external file. Scripts in the actual page are not found. For instance, with the following in HEAD:

<head>
    <script type="text/javascript" src="jquery.js" id="jquery"></script> 
    <script type="text/javascript" src="jquery-ui.js" id="ui"></script> 
    <script type="text/javascript" id="custom">
        $(document).ready( function() {
            $("script[type*=javascript]").each(function() {
                alert("Found script "+this.id);
            });         
            $("script[type*=html]").each(function() {
                alert("Found TEMPLATE script "+this.id);
            });         
        });
    </script> 
    <script id="filter-test" type="text/html">
        <dt>Test</dt>
    </script>
</head>
<body>
    <script id="filter-search" type="text/html">
        <dt>Search</dt>
        <dd><input type="text"/></dd>
    </script>
</body>

I get the following alerts:

  • Found script jquery
  • Found script ui

The custom and filter-test scripts in the HEAD are not selected, nor is the filter-search script in the body tag.

Is this the expected behavior? Why does this not work? I can work around it, but it is annoying that it doesn't work.

© Stack Overflow or respective owner

Related posts about jQuery