0

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>
1
  • 2
    The newly-created script element is not in the DOM before you insert it. Commented Jun 25, 2019 at 10:22

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

Comments

1

Please have a look at the following documentation for setAttribute. You can do like this

b.setAttribute("name", "helloButton");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.