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)
HTML | <script> type Attribute It has a Default value which is “text/javascript”. Attribute Values: It contains a single value i.e media_type which specifies the MIME type of script.
The type attribute specifies the type of the script. The type attribute identifies the content between the <script> and </script> tags.
Just type the name of the element without "<" and ">" characters. For example type P, not <P> if the answer is the <P> element.
The type attribute gives the language of the script or format of the data.
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...)
Because what you wrote means: find every script
element with an attribute type
being equal to store
and being a descendant of #target
(because of the space).
You could do something like:
var sel = $('script#target[type="store"]');
but this is unnecessary, because an ID already identifies an element - no elements in a document can share the same ID.
If I understand your description well, what you need is:
var sel = $('script[type="store"]');
One more thing: you should not use the type
attribute for this. It has a very specific purpose:
The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. The default, which is used if the attribute is absent, is "text/javascript".
So I suggest you use data-type
instead of type
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With