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!
36 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 href = test.html></a> </body> </html> 0Try this :
<script src=""></script> <script type="text/javascript"> $(document).ready(function () { var simpleText = "hello_world"; var finalSplitText = simpleText.split("_"); var splitText = finalSplitText[0]; $("#target").text(splitText); }); </script> <body> <a href = test.html></a> </body> </html> <html> <head> <script> function putText() { var simpleText = "hello_world"; var finalSplitText = simpleText.split("_"); var splitText = finalSplitText[0]; document.getElementById("destination").innerHTML = "I need the value of " + splitText + " variable here"; } </script> </head> <body onLoad = putText()> <a href = test.html>I need the value of "splitText" variable here</a> </body> </html> Although, I must say that what you are asking to do is not a good way to do it. A good way is this:
In raw javascript, you'll want to put an id on your anchor tag and do this:
<html> <script> var simpleText = "hello_world"; var finalSplitText = simpleText.split("_"); var splitText = finalSplitText[0]; function insertText(){ document.getElementById('someId').InnerHTML = splitText;} </script> <body onload="insertText()"> <a href = test.html>I need the value of "splitText" variable here</a> </body> </html> The info inside the <script> tag is then processed inside it to access other parts. If you want to change the text inside another paragraph, then first give the paragraph an id, then set a variable to it using getElementById([id]) to access it ([id] means the id you gave the paragraph). Next, use the innerHTML built-in variable with whatever your variable was called and a '.' (dot) to show that it is based on the paragraph. You can set it to whatever you want, but be aware that to set a paragraph to a tag (<...>), then you have to still put it in speech marks.
Example:
<!DOCTYPE html> <html> <body> <!--\|/id here--> <p></p> <p></p> <script> <!--Here we retrieve the text and show what we want to write... var text = document.getElementById("myText"); var tag = document.getElementById("myTextTag"); var toWrite = "Hello" var toWriteTag = "<a href=' Overflow</a>" <!--...and here we are actually affecting the text.--> text.innerHTML = toWrite tag.innerHTML = toWriteTag </script> <body> <html>