'How to make environmental variables equal to ID Values in html

Below is my API reference call. I am using github so I put the key in a seperate file and protected that file using .gitignore.

The issue is I have no Idea how to get that key from my javascript file into the HTML data-key using a variable.

<div 
    id="wg-api-football-fixtures"
    data-host="api-football-v1.p.rapidapi.com"
    data-refresh="15"
    data-date="2022-05-06"
    data-key = "NEED MY API KEY HERE!"
    data-theme="false"
    data-show-errors="false"
    class="api_football_loader">    
</div>

I'm new to this so I could be doing something wrong, let me know.



Solution 1:[1]

Your api key file:

// api_key.js
var apiKey = "123456789ABCDEFGH";

Your main javascript file:

// main.js
document.querySelector('div#wg-api-football-fixtures').setAttribute('data-key', apiKey);

In your html file ...

<div 
    id="wg-api-football-fixtures"
    data-host="api-football-v1.p.rapidapi.com"
    data-refresh="15"
    data-date="2022-05-06"
    data-key = "NOT_LOADED_YET"
    data-theme="false"
    data-show-errors="false"
    class="api_football_loader">
</div>
<script type="text/javascript" src="api_key.js"></script>
<script type="text/javascript" src="main.js"></script> 

Just make sure that you call the code in main.js after you included the api_key.js and after the html is loaded.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Schokokuchen Bäcker