Categories
JavaScript Answers

How to pass parameters to JavaScript files?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *