javascript code to reset items in dom

Solutions on MaxInterview for javascript code to reset items in dom by the best coders in the world

showing results for - "javascript code to reset items in dom"
Glen
08 Jan 2020
1<body>
2    <label>Input:</label>
3    <input type="text" id="myInput">
4    <button onclick="add_Item()">ADD ITEMS</button>
5    <button onclick="search_Item()">SEARCH ITEMS</button>
6    <button onclick="reset_Item()">RESET</button>
7    <div id="items"></div>
8</body>
9<script>
10
11var arr=[];
12function add_Item(){
13var inpt=document.getElementById("myInput");
14// console.log(inpt);
15var para=document.createElement("p");
16para.textContent=inpt.value;
17var parent=document.getElementById("items");
18parent.appendChild(para);
19arr.push(inpt.value);
20inpt.value="";
21}
22function search_Item(){
23    var srch=document.getElementById("myInput");
24    var index=-1;
25    for(var i=0;i<arr.length;i++){
26        if(arr[i] == srch.value){
27            index=i;
28            break;
29        }
30    }
31    var parent=document.getElementById("items");
32        var childrens=parent.querySelectorAll("p");
33        for(var i=0;i<childrens.length;i++){
34            // childrens[i].style.background="white"; //for highlighting the matched one while keeping others
35            childrens[i].remove();
36        }
37    if(index>=0){
38        var matchedItem=document.createElement("p");
39        matchedItem.style.backgroundColor="yellow";
40        matchedItem.textContent=arr[index];
41        parent.appendChild(matchedItem);
42    }
43
44}
45function reset_Item(){
46    var parent=document.getElementById("items");
47    var childrens=parent.querySelectorAll("p");
48    for(var i=0;i<childrens.length;i++){
49       childrens[i].remove();
50    }
51    for(var i=0;i<arr.length;i++){
52        var item=document.createElement("p");
53        item.textContent=arr[i];
54        parent.appendChild(item);
55    }
56}
57
58</script>