0

I have a task to create like comment box in the HTML and Javascript How to delete comment using button delete? or should i use linked list in this task? This is my code:

<html>
    <body>
        <div id='container'>
            <textarea id='txt'></textarea><br/>
            <button type='button' onclick="add()">Enter</button>
            <div id='contents'></div>
        </div>

        <script>
            function add(){
                var txt= document.getElementById('txt').value;
                var content= document.getElementById('contents');
                var tes= '<hr/><span>'+txt+"</span><button type='button'>delete</button>";
                content.innerHTML+=tes;
            }
        </script>
    </body>
</html>
Matúš Dúbrava
  • 771
  • 5
  • 18
Scramble
  • 119
  • 10

3 Answers3

0

To answer the question quick, if you wanna stick with pure javascript, you can remove element from DOM using his Parent, take a look at this Remove element by id

P.S Don't you need a way to store your comments somewhere (database?)

P.S.2 You should avoid using html tags directly in a string assigned to a variable. Maybe you should take a look at some best practice over the web (regarding DOM manipulation, jQuery clone() method etc)

Hope it helps

Community
  • 1
  • 1
0

It seems to me that you're not worried about persisting your data. So the quickest fix would be:

   <script>
            var arr = 1;
            function del(comm_id){
               var dom =document.getElementById(comm_id);
               dom.parentNode.removeChild(dom);
            }

        function add(){
            var txt= document.getElementById('txt').value;
            var content= document.getElementById('contents');
            var comm_id="comment"+arr;
            var del_id="delete"+arr;
            var tes= "<div id="+comm_id+">"+'<hr/><span>'+txt+"</span><button type='button' id="+ del_id + ">delete</button></div>";
            content.innerHTML+=tes;
             document.getElementById(del_id).setAttribute('onclick',"del('"+comm_id+"')");
            arr++;
        }
    </script>
Nayeem Zen
  • 2,569
  • 1
  • 17
  • 16
0

For this there is no need of implementing Linked List. You can make use of Array in javascript. There is no need of pre-defining the size of array. You can add any number of elements in it.

To remove a particular element you can make use of

array.splice(i, 1);

This will remove the ith element.