使用document.getElementByID访问动态生成的DIV

时间:2018-02-14 10:21:56

标签: javascript html forms interactive

我正在尝试使用document.getElementById访问动态生成的DIV,但是获取不能将属性innerHTML设置为null,这很明显。

基本上我正在尝试构建一种类似于https://www.typeform.com/

的交互式表单

我想为每个问题创建单独的DIV。

这是我到目前为止所做的:

的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";
  }
}

1 个答案:

答案 0 :(得分:2)

document.getElementById通过其ID 从文档获取一个元素。

您尚未将div添加到文档中,因此无法找到它。

那说你已经有了元素!没有必要在文档或其他任何地方搜索它。

newDiv.innerHTML = html2;