-3

actually i am making a todolist so i want to replace div which i added through in innerhtml with tr and after created of the first row in html please check

Html Part:

<table id="ws-table" class="table table-bordered">
    <tr id="insert">
        <th>#</th>
        <th>Date</th>
        <th>Items</th>
        <th>Edit / Delete</th>
     </tr>
    <!-- Here i wanted an tr
</table>

actually i am making a todolist so i want to replace div which i added through in innerhtml with tr and after created of the first row in html please check

javascript part :

                var takeInput;
            var DATA = [];
            load();

            function insertItem(){
                takeInput = document.getElementById('item').value;

                DATA.push(takeInput);
                renderJson(DATA);
                document.getElementById('item').value = "";
            }

            function renderJson(data){
                document.getElementById('container').innerHTML = "";

                for(var i in data){
                    container.innerHTML = container.innerHTML + "<div id=" + i + " onclick='removeItem(this.id)'><input type='checkbox'/><label>"+data[i]+"</label></div>";
                }
                save();
            }

            function removeItem(Id){
                var itemId = document.getElementById(Id);

                if(itemId.childNodes[0].checked == true){
                    var arr_ind = DATA.indexOf(itemId.childNodes[1].innerText);
                    DATA.splice(arr_ind,1);

                    itemId.parentNode.removeChild(itemId);
                    save();
                }
            }

            function save(){
                localStorage.myList = JSON.stringify(DATA);
            }

            function load(){
                DATA = JSON.parse(localStorage.myList);
                renderJson(DATA);
            }
khurram khan
  • 159
  • 1
  • 7

1 Answers1

1

Element.innerHTML is for replacement only, so you need to read it first concatenate with new row and then assing back, better use Element.insertAdjacentHTML():

var row = "<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>";
document.querySelector("#ws-table tbody").insertAdjacentHTML("beforeend", row);

You may want to use thead for your table header. Check this thread for more information.

Community
  • 1
  • 1
Leonid Vasilev
  • 11,910
  • 4
  • 36
  • 50