0

My JavaScript code works up to the last append. This I checked with alert messages. All the alerts except for the last one get displayed. So I assume the problem is with the last append. Can someone please help?

var node = document.createElement("li");
var d0 = document.createElement("div");

var d1 = document.createElement("div");
var L1 = document.createElement("label");

d1.append(L1);

L1.innerHTML = "datah[key]";


var d2 = document.createElement("div");
var L2 = document.createElement("label");
d2.append(L2);

L2.innerHTML = "datah1[key]";

console.log("test1");
d0.append(d1);
d0.append(d2);

node.append(d0);
console.log("test2");

document.getElementById("speclist").appendChild(node);
// The following alert doesn't get printed
console.log("test3");
<div>
  <ul id="speclist">

  </ul>
</div>
shrys
  • 5,381
  • 2
  • 15
  • 29
Mia Davis
  • 121
  • 8
  • 6
    "All the alerts except for the last one get displayed" — The last one is displayed when I run that code. – Quentin Jul 05 '19 at 09:51
  • Look at the Console in your browser's developer tools. Read the error messages. – Quentin Jul 05 '19 at 09:52
  • 10 to 1 says [this is a duplicate](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Quentin Jul 05 '19 at 09:52
  • 1
    All alerts displayed when I run the code. – chirag Jul 05 '19 at 09:53

1 Answers1

0

There is no problem with last append problem is that you are not wrapping "test3" in any html.you want to show test3 then you have to wrap it with node(li).

var node = document.createElement("li");
var d0 = document.createElement("div");

var d1 = document.createElement("div");
var L1 = document.createElement("label");

d1.append(L1);

L1.innerHTML = "datah[key]";


var d2 = document.createElement("div");
var L2 = document.createElement("label");
d2.append(L2);

L2.innerHTML = "datah1[key]";

alert("test1");
d0.append(d1);
d0.append(d2);

node.append(d0);
alert("test2");

//document.getElementById("speclist").appendChild(node);
// The following alert doesn't get printed
alert("test3");

  node.appendChild(document.createTextNode("test3"));
  document.getElementById("speclist").appendChild(node);
<div>
  <ul id="speclist">

  </ul>
</div>

and one more thing when i am running your code it is showing me 3 alerts test1,test2 and test3.

Bhawana
  • 176
  • 6