0

I want to inject text into a div using a variable. Here's a Stack Snippet of my code:

tDNA() {
  var dna = prompt("Enter the DNA: ");
}
document.getElementById("dna").innerHTML = "DNA: " + dna;
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <src="main.js">
    <div id="dna"></div>
</body>

</html>


function promp

5
  • "src" is not an element. You want to be using <script src="main.js"></script> to load your main.js file. And you need to do something to actually fire the promptDNA function and you need to move the document.getElementById.... into that function as well. Commented May 15, 2018 at 22:17
  • 1
    your dna is being used out of scope Commented May 15, 2018 at 22:18
  • See stackoverflow.com/questions/40858456/… Commented May 15, 2018 at 22:21
  • Besides, you should use element.textContent instead of innerHTML. Using innerHTML for user input is an XSS vulnerabiliy. Commented May 15, 2018 at 22:22
  • 1
    Possible duplicate of how to display a javascript var in html body Commented May 15, 2018 at 22:24

3 Answers 3

1

You need to import your script like this

<script type="text/javascript" src="main.js"></script>
Sign up to request clarification or add additional context in comments.

1 Comment

type="text/javascript" is not required, and even not recommended.
0

You can try this out.

HTML

<html>
<head>
</head>
<body>
<script defer src = "main.js"></script>
    <div id = "dna">
      <p></p>
    </div>
</body>
</html>

JavaScript

function promptDNA(){
    var dna = prompt("Enter the DNA: ");
    d1 = document.querySelector("p");   
    d1.textContent = dna;
}

promptDNA();

2 Comments

Your script is executed before the DOM is initialized. You need to wait for the DOM to initialize or use the script tag at the end of the HTML.
@ssc-hrep3 Added defer in script tag.
0

Like this, you have to add the data to the HTML where the variable dna is in scope and then actually call the function

function promptDNA(){
    var dna = prompt("Enter the DNA: ");
    document.getElementById("dna").textContent = "DNA: " + dna;
}

promptDNA()
<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <div id="dna"></div>
    <script src="main.js"></script>
</body>
</html>

Also, you're importing your script improperly.

2 Comments

I also had to add "onload = "promptDNA()" to get it to work, thanks for the help!
Your script is executed before the DOM is initialized. You need to wait for the DOM to initialize or use the script tag at the end of the HTML.

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.