1

I am trying to turn an HTML id to a Javascript variable, the reason is I want to retrieve another variable from another file, I ended up having the variable in HTML format, and I would like to use that variable in the javascript script. Is there a simple way to solve this problem? Because my code doesn't seem to be working. Thank you

<!DOCTYPE html>
<head>
  <div id="theVariable">13579</div>
  <script type="text/javascript">
    var converted = document.getElementById("theVariable").value;
    //var converted = document.getElementById("theVariable");
    document.write(converted);
    document.write(" something else");
  </script>
</head>

<!---------out put should be: --------
13579
13579 something else
--------------------------------------->

1
  • Have you tried to include the link of javascript file on <script> instead of print it all on HTML? Commented Feb 1, 2018 at 3:09

3 Answers 3

2

You are trying to use the attribute value on a div element which wont work. Use innerhtml instead

<!DOCTYPE html>
<head>
  <div id="theVariable">13579</div>
  <script type="text/javascript">
    var converted = document.getElementById("theVariable").innerHTML;
    //var converted = document.getElementById("theVariable");
    document.write(converted);
    document.write(" something else");
  </script>
</head>

<!---------out put should be: --------
13579
13579 something else
--------------------------------------->

Sign up to request clarification or add additional context in comments.

Comments

0

You can use textContent & trim.trim will remove any white space

var converted = document.getElementById("theVariable").textContent.trim();
console.log(converted)
<div id="theVariable">13579</div>

Comments

0

.value uses to get value in input tag. for div/span/p, we should use innerHTML

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.