Reputation: 3414
I am trying to add data-client-key
in my dynamically created JavaScript attribute. Check below code what I have tried:
var script = document.createElement("script")
script.type = "text/javascript";
script.src = 'https://app.example.com/snap/script.js';
//script.data-client-key="CLIENT-KEY-HERE"; /* showing error message */
document.getElementsByTagName(script)[0].setAttribute("data-client-key", "CLIENT-KEY-HERE"); /* Uncaught TypeError: Cannot read property 'setAttribute' of undefined */
document.getElementsByTagName("head")[0].appendChild(script);
My output should be like below when I inspect element:
<script src="https://app.example.com/snap/script.js" data-client-key="CLIENT-KEY-HERE"></script>
Upvotes: 0
Views: 3261
Reputation: 603
Please have a look at the following documentation for setAttribute. You can do like this
b.setAttribute("name", "helloButton");
Upvotes: 1
Reputation: 5960
Change
document.getElementsByTagName(script)[0].setAttribute("data-client-key", "CLIENT-KEY-HERE");
to
script.setAttribute("data-client-key", "CLIENT-KEY-HERE");
as you already have your script element in script
variable
Upvotes: 7