Home Accessing dynamically generated DIV using document.getElementByID
Reply: 1

Accessing dynamically generated DIV using document.getElementByID

s4tr2
1#
s4tr2 Published in 2018-02-14 10:21:55Z

I am trying to access a dynamically generated DIV using document.getElementById but getting cannot set property innerHTML of null and that's pretty obvious.

Basically I am trying to build a type of interactive form just like https://www.typeform.com/

I want to create seperated DIV's for each question.

Here is what I have done so far:

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Interactive Forms</title>
    <script src="script.js"></script>
  </head>
  <body>
    <center>
      <div id="playArea">
          <h3>Hello Stranger! Let's start</h3> <br/>
          <button id="start" onclick="Questions()">Let's start</button><span>or Hit Enter</span>
      </div>
    </center>
  </body>
</html>

script.js

    var questions = [
    "Hey, what's you name?",
    "Can I know your E-mail ID please?",
    "Would you also like to subscribe to the newsletter?"
];
var html = "";
var i =0;
addEventListener("keydown", function(event){
  if(event.keyCode==13){
    Question();
  }
  if(event.code==39){
    nextQuestion();
  }
});
function Question(){
    html = questions[0]+"<br>"+"<input type='text' class='answer'><button onclick='nextQuestion()'>Ok</button><span>or Hit Right Arrow</span><br>";
    document.body.innerHTML = html;
    // document.getElementById("playArea").innerHTML = html;
    i++;
}
function nextQuestion(){
  if(i<questions.length){
    var html2 = "";
    newDiv = document.createElement("div");
    check="'answer"+i+"'";
    console.log("'answer"+i+"'");
    newDiv.setAttribute("id", "'answer"+i+"'");
    console.log(newDiv.id);
    html2 = questions[i]+"<br><input type='text' id='answer'><button onclick='nextQuestion()'>Ok</button><span>or Hit Right Arrow</span><br>";
    newDiv.innerHTML = html2;
    oQ = document.getElementById("otherQuestions");
    document.body.insertBefore(newDiv, oQ);
    i++;
}
  else{
  document.body.innerHTML = "Thank you for the response";
  }
}
Quentin
2#
Quentin Reply to 2018-02-14 10:25:50Z

document.getElementById gets an element, by its ID, from the document.

You haven't added the div to the document yet, so it can't be found.


That said you already have the element! There's no need to search for it, in the document or anywhere else.

newDiv.innerHTML = html2;
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.317965 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO