Search code examples
javascripthtmlattributes

how to console.log html tag attribute's value with hyphen in the middle in JavaScript?


I would need some help about this attribute:

<script id="mysdk" src="https://www.myscript.com/sdk/js?currency=EUR" this-client-token="nsiYXV0aG9yaXphdGlvbkZpbmdlcnByaW50IjoiZGUyYjM4N2FiZWV"></script>

What I'm trying to do is to console.log this-client-token in this way:

    var el = document.getElementById("mysdk");
    console.log(el.this-client-token);

This because, after making this work, I will be finally able to change the value of this-client-token, since that is my purpose. But I get the following error in the console:

Uncaught ReferenceError: client is not defined

I have no idea why I get this error, is it because of the hyphen? any suggestion?

Thank you!

Elliot


Solution

  • It doesn't work because - is subtraction. It's trying to calculate el.this - client - token, which fails because none of these variables exist.

    Change to a data-XXX attribute, and use the dataset property.

    var el = document.getElementById("mysdk");
    console.log(el.dataset.clientToken);
    <script id="mysdk" src="https://www.myscript.com/sdk/js?currency=EUR" data-client-token="nsiYXV0aG9yaXphdGlvbkZpbmdlcnByaW50IjoiZGUyYjM4N2FiZWV"></script>

    If you can't change the attribute (because it's required by the SDK script, which you can't change) you can use el.getAttribute("this-client-token")