How to find <script> elements with particular value of "type" attribute?

0xC0DEGURU picture 0xC0DEGURU · Jun 7, 2013 · Viewed 42.3k times · Source

Assuming the following script tag in a random HTML document:

<script id="target" type="store">
    //random JavaScript code
    function foo(){
       alert("foo");
    }
    foo();
</script>

can anybody explain why the following expression doesn't find all elements of script with value store for their type attribute.

var sel = $('#target script[type="store"]');

jQuery version: v1.7.2 Chrome version: 25.0.1364.172 (running on Debian Squeeze)

Answer

Christofer Eliasson picture Christofer Eliasson · Jun 7, 2013

Your selector $('#target script[type="store"]') would match any script tag with type store that is a child of the element with id target. Which isn't the case for your example HTML.

If you want to select all script tags with type store, your selector should look something like this: $('script[type="store"]').

If you only want to select the particular script tag that has id target, you could use $('#target') only. No need to be more specific as the ID should be unique to that element. Using only the ID selector would be more efficient as well, since jQuery then could utilize the native document.getElementById() to select your element (a micro-optimization perhaps, but still...)