javascript code to search items in dom

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

showing results for - "javascript code to search items in dom"
Lola
14 Sep 2018
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    <div id="items"></div>
7</body>
8<script>
9
10var arr=[];
11function add_Item(){
12var inpt=document.getElementById("myInput");
13// console.log(inpt);
14var para=document.createElement("p");
15para.textContent=inpt.value;
16var parent=document.getElementById("items");
17parent.appendChild(para);
18arr.push(inpt.value);
19inpt.value="";
20}
21function search_Item(){
22    var srch=document.getElementById("myInput");
23    var index=-1;
24    for(var i=0;i<arr.length;i++){
25        if(arr[i] == srch.value){
26            index=i;
27            break;
28        }
29    }
30    var parent=document.getElementById("items");
31        var childrens=parent.querySelectorAll("p");
32        for(var i=0;i<childrens.length;i++){
33            // childrens[i].style.background="white"; //for highlighting the matched one while keeping others
34            childrens[i].remove();
35        }
36    if(index>=0){
37        var matchedItem=document.createElement("p");
38        matchedItem.style.backgroundColor="yellow";
39        matchedItem.textContent=arr[index];
40        parent.append(matchedItem);
41    }
42
43}
44
45</script>