Ali Tor Ali Tor - 6 months ago 14
Javascript Question

Why doesn't creating DIV element using JQuery work?

I am trying to create a div element with class and append a child it. But I am not getting any response. What might be the reason?

JS content

function createTable() {
var procDiv = $("<div class='proc-container'></div>");
var procUl = $("<ul></ul>")
for (var i = 0; i < 3; i++) {
var li = $("<li></li>")
li.innerText = "P" + i;
procUl.appendChild(li);
}
procDiv.appendChild(procUl);

$(".container").get(0).appendChild(procDiv);


}

index.html

<html lang="en">
<head>
<title>Title</title>
<script src="jquery-1.12.3.min.js"></script>
<link rel="stylesheet" href="reset.css">
<link rel="stylesheet" href="style.css">
<script src="ga.js"></script>
</head>
<body onload="createTable(1,1,1)">
<div class="container">
</div>
</body>
</html>

Answer

li jQuery object does not have .innerText property; procUL jQuery object does not have .appendChild() method. Substitute using jQuery objects for DOM elements; .text() for .innerText, .append() for .appendChild()

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
  function createTable() {
    var procDiv = $("<div class='proc-container'></div>");
    var procUl = $("<ul></ul>")
    for (var i = 0; i < 3; i++) {
      var li = $("<li></li>")
      li.text("P" + i);
      procUl.append(li);
    }
    procDiv.append(procUl);
    $(".container").append(procDiv);
  }
</script>

<body onload="createTable()">
  <div class="container">
  </div>
</body>

Comments