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
AAM111
  • 1,178
  • 3
  • 19
  • 39
  • "src" is not an element. You want to be using 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. – Kurt May 15 '18 at 22:17
  • 1
    your dna is being used out of scope – Hooman Bahreini May 15 '18 at 22:18
  • See https://stackoverflow.com/questions/40858456/how-to-display-a-javascript-var-in-html-body – cacti5 May 15 '18 at 22:21
  • Besides, you should use [element.textContent](https://developer.mozilla.org/pl/docs/Web/API/Element/textContent) instead of `innerHTML`. Using `innerHTML` for user input is an XSS vulnerabiliy. – Frax May 15 '18 at 22:22
  • 1
    Possible duplicate of [how to display a javascript var in html body](https://stackoverflow.com/questions/40858456/how-to-display-a-javascript-var-in-html-body) – Frax May 15 '18 at 22:24

3 Answers3

1

You need to import your script like this

<script type="text/javascript" src="main.js"></script>
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
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.

Jonathan Rys
  • 1,782
  • 1
  • 13
  • 25
  • I also had to add "onload = "promptDNA()" to get it to work, thanks for the help! – AhPawLow May 15 '18 at 23:26
  • 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 May 20 '18 at 23:07
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();
Mihir
  • 73
  • 1
  • 10