Can I use a custom attribute in a script
tag such as:
Can I use a custom attribute in a script tag such as:
Yes, using data-* attributes:
And then use the contained javascript to access the value of 'mycustomattribute'?
Yes, probably. If you give the script
tag an id
, you can do it reliably:
var info = document.getElementById("theId").getAttribute("data-info");
Otherwise, you have to make assumptions about the script tag. If it's always in the markup of the page (not added later using code), you can do this:
var scripts = document.getElementsByTagName("script");
var info = scripts[scripts.length - 1].getAttribute("data-info");
That's because if the script tag is in the markup, it's run as soon as it's encountered (unless async or defer is used [and supported by the browser]), and will always be the last script tag on the page (at that point in time). But again, if code adds the script tag later, using createElement
and appendChild
or similar, you can't rely on that.
Here's a complete example: Live Copy
Data on Script Tags