Search code examples
javascriptjquerygridster

Dynamic creation of list and adding HTML Tags in the each newly created element


I am using gridster for one of my project and my main aim is to create the widgets dynamically.The number of widgets I need to create will come from backend(Django).But for now I want to write a simple javascript code to create the widgets dynamically and I am hardcoding the value of the number of dynamic widgets After reading a bit I found the following code

<ul>
<script type="text/javascript">
var ul = document.createElement("ul");
document.body.appendChild(ul);

for (var i = 1; i <= 3; i++)
{
   var li = document.createElement("li");  
   li.className = "file";

   var a = document.createElement("a");
   a.innerHTML = 1;

  li.appendChild(a);
  ul.appendChild(li);
}

</script>

But my one li element is like following

 <li data-row="1" data-col="1" data-sizex="1" data-sizey="1"><button class="delete-button" style="float: right;">-</button><h3>1</h3></li>

So in above code I am replacing

a.innerHTML = 1; 

with

a.innerHTML =<button class="delete-button" style="float: right;">-</button>
<h3>3</h3>

But this is not working at all.I even know that this is not exactly what I want But this is just a step before the actual desired output

This is just 2nd day I have started with jquery/javascript and gridster Any help would be appreciated


Solution

  • a.innerHTML =<button class="delete-button" style="float: right;">-</button>
    <h3>3</h3>
    

    You are trying to append elements to another element. This means that a will become the parent element, and button and h3 will become child elements.

    To do this we first have to create the button like so:

    var button = document.createElement('button');
    button.classList.add('delete-button');
    button.style.cssFloat = 'right';
    

    Then we create the h3:

    var h3 = document.createElement('h3');
    h3.innerHTML = '3';
    

    Then we append the elements to the a:

    a.append(button);
    a.append(h3);
    

    This should do what you want :)