I am trying to add a UL inside of a LI. I have an HTML tree that looks like this:
<li id="node0"><a href="#" onclick="Collapse(event)"><img src="file:///C:/drag-drop-folder-tree/images/dhtmlgoodies_minus.gif"></a>All My Windows
<ul style="display: block;" id="tree_ul_0">
<li id="node0" ondragenter="return dragEnter(event)" ondragover="allowDrop(event)" ondrop="drop(event)" ondragstart="drag(event)" draggable="True"><a href="#">9:00-9:30 moving up</a></li>
<li id="node1" ondragenter="return dragEnter(event)" ondragover="allowDrop(event)" ondrop="drop(event)" ondragstart="drag(event)" draggable="True"><a href="#">9:00-9:30 moving down</a>
I am trying to use Javascript to add a new UL that will be a child of the LI node0 at the top.
Here is my code:
var newul = document.createElement("ul");
var ulist = document.getElementById("node0");
var newItem = document.createElement("li");
newItem.innerHTML = "<ul id='item1'><li id='Item0' ondragenter='return dragEnter(event)' ondragover='allowDrop(event)' ondrop='drop(event)' ondragstart='drag(event)' draggable='True'><a onclick='Collapse(event)' href='#'><img src='dhtmlgoodies_minus.gif'></a><text>hello</text></li></ul>"
ulist.appendChild(newItem);
When I execute this code, I end up with:
<li>
<ul id="item1">
<li id="Item0" ondragenter="return dragEnter(event)" ondragover="allowDrop(event)" ondrop="drop(event)" ondragstart="drag(event)" draggable="True"><a onclick="Collapse(event)" href="#"><img src="dhtmlgoodies_minus.gif"></a><text>hello</text>
</li>
</ul>
</li>
So it adds a new:
<LI>
which is a child of node0
I would like for my item1 UL to be the child of node0. Can you tell me how to add the UL without getting the extraneous LI?
You overcomplicated it. You already got the node and you can just set its innerHTML:
Alternatively, you can create an ul and an li in it and add that, but then you need to set add the proper element, the ul, to the node. That could easily become a lot of code. The snippet below doesn't even set all events and it doesn't create the
a
element inside the node.In your current situation you mixed both. You create a new
ul
, which is never used. Then you create a newli
. Then you set the innerHTML of thatli
to the entire HTML chunk you want to have, and add it to the parent. Theli
you get in your document is thenewitem
you created in your code.