无法在“节点”上执行“ appendChild”:新的子元素包含父项下拉问题

时间:2019-07-05 16:59:23

标签: javascript html dom

我正在创建一个自动完成div下拉菜单。

a = document.createElement("DIV");
    a.setAttribute("id","autocomplete-list");
    a.setAttribute("class", "autocomplete-items");
    /*append the DIV element as a child of the autocomplete container:*/


    b = document.createElement("DIV");
    b.classList.add("row", "no-gutters")
    for (i = 0; i < arr.length; i++) {
        /*check if the item starts with the same letters as the text field value:*/

          /*create a DIV element for each matching element:*/
          b = document.createElement("DIV");
          /*make the matching letters bold:*/
        //   b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
          b.innerHTML += arr[i]
          /*insert a input field that will hold the current array item's value:*/
          b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
          /*execute a function when someone clicks on the item value (DIV element):*/
              b.addEventListener("click", function(e) {
              /*insert the value for the autocomplete text field:*/
              inp.value = this.getElementsByTagName("input")[0].value;
              /*close the list of autocompleted values,
              (or any other open lists of autocompleted values:*/
              closeAllLists();
          });
          a.appendChild(b);

      }
    $(b).on('click', '#dropWrapper', function () {
        console.log('on click fired')
        /*insert the value for the autocomplete text field:*/


        var inputs2 = this.querySelectorAll(".col-4"); // returns all element

        inputs2.forEach(ele => {
            // check for the particular class
            if (ele.getAttribute("class") == "col-4 querySelect") {
                console.log('here')

                console.log(ele.textContent)
                inp.value = ele.textContent
                retrieveOrderDetails(inp.value)
            }
        })

        /*close the list of autocompleted values,
        (or any other open lists of autocompleted values:*/

    })
        a.appendChild(b);
        inp.parentNode.appendChild(a);
        document.getElementById("autocomplete-list").appendChild(a);

出现下拉菜单,但出现以下错误:

  

无法在“节点”上执行“ appendChild”:新的子元素包含父元素。

在此行

document.getElementById("autocomplete-list").appendChild(a);

我无法弄清楚错误的含义。

1 个答案:

答案 0 :(得分:1)

我看到您在代码顶部将a的{​​{1}}定义为id。然后在底部尝试用autocomplete-list aid附加到元素上。在尝试将元素作为孩子追加到自身时,存在某种递归。