Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript variable access in HTML

Tags:

javascript

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!

like image 601
Damien-Amen Avatar asked Feb 13 '13 03:02

Damien-Amen


People also ask

Can we access JavaScript variable in HTML?

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.

Can I use variables in HTML?

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.

How do you access variables in JavaScript?

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.


1 Answers

<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> 
like image 92
kufudo Avatar answered Sep 24 '22 05:09

kufudo