Sometimes, we want to pass parameters to JavaScript files.
In this article, we’ll look at how to pass parameters to JavaScript files.
How to pass parameters to JavaScript files?
To pass parameters to JavaScript files, we can store data in data attributes.
For instance, we write
<script id="helper" data-name="helper" src="helper.js"></script>
to add a script element with the data-name
attribute.
Then we get the value of the data-name
attribute with
const name = document.getElementById("helper").getAttribute("data-name");
We call getAttribute
with 'data-name'
to return the value of the data-name
attribute after selecting the script element with getElementById
.
Conclusion
To pass parameters to JavaScript files, we can store data in data attributes.