Say I have the following JavaScript in a HTML page
<html> <script> var simpleText = "hello_world"; var finalSplitText = simpleText.split("_"); var splitText = finalSplitText[0]; </script> <body> <a href = test.html>I need the value of "splitText" variable here</a> </body> </html>
How do I get the value of the variable "splitText" outside the script tags.
Thanks!
There are three ways to display JavaScript variable values in HTML pages: Display the variable using document. write() method. Display the variable to an HTML element content using innerHTML property.
Use the <var> tag in HTML to add a variable. The HTML <var> tag is used to format text in a document. It can include a variable in a mathematical expression.
In JavaScript, variables can be accessed from another file using the <script> tags or the import or export statement. The script tag is mainly used when we want to access variable of a JavaScript file in an HTML file. This works well for client-side scripting as well as for server-side scripting.
<html> <script> var simpleText = "hello_world"; var finalSplitText = simpleText.split("_"); var splitText = finalSplitText[0]; window.onload = function() { //when the document is finished loading, replace everything //between the <a ...> </a> tags with the value of splitText document.getElementById("myLink").innerHTML=splitText; } </script> <body> <a id="myLink" href = test.html></a> </body> </html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With