0

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>

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. Such simple beginner mistakes always exist.
1

Your proc variables are being assigned jQuery objects. Consider using jQuery's .append() method.

$(".container").append(procDiv);

1 Comment

At first glance presumed that li.innerText = "P" + i would log an error at console, though appears to set the property at the jQuery li object, though not at DOM element <li> .innerText property

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.