Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data attribute of script tag?

Tags:

javascript

Say I've got the following script tag:

<script async data-id="p3PkBtuA" src="//example.com/embed.js"></script> 

Within that embed.js file, how can I get the value of data-id attribute?

I'm trying to keep the embed.js file as light as possible, so ideally it wouldn't need to use some sort of javascript library.

like image 782
Shpigford Avatar asked Feb 15 '13 22:02

Shpigford


People also ask

How do you get the value of a data attribute?

To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written.

How do you get the value of data attribute in JS?

Approach: First, select the element which is having data attributes. We can either use the dataset property to get access to the data attributes or use the . getAttribute() method to select them by specifically typing their names.

How get value of data attribute in CSS?

The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.


1 Answers

For modern browsers that support html5 you can use document.currentScript to get the current script element.

Otherwise, use querySelector() to select your script element by id or attribute.

Note that we don't use the src attribute because that can be fragile if you're delivering over a CDN or with differences between development and production environments.

embed.js

(function(){     // We look for:     //  A `script` element     //  With a `data-id` attribute     //  And a `data-name` attribute equal to "MyUniqueName"     var me = document.querySelector('script[data-id][data-name="MyUniqueName"]');     var id = me.getAttribute('data-id'); })(); 

In the host html:

<script async    data-id="p3PkBtuA"    data-name="MyUniqueName"    src="//example.com/embed.js"> </script> 

This approcah has the downside that you couldn't successfully embed two identical scripts. This is a pretty rare case, but could happen.

Note that I would personally us data-id to select the script instead of passing data, and would place the unique data in a more descriptive tag:

<script async    data-id="MyUniqueName"    data-token="p3PkBtuA"    src="//example.com/embed.js"> </script> 

which would let me use this following:

var token = document   .querySelector('script[data-id="MyUniqueName"][data-token]')   .getAttribute('data-token'); 
like image 130
brice Avatar answered Sep 20 '22 16:09

brice