我想将孩子添加到div。
<div class="d-flex quantityReceived" id="quantityReceived">
<button type="button" class="btn btn-info changeValue" onclick="allOrderType()"><div id="spinner"><i class="fas fa-caret-down"></i></div></button>
<input name="order" class="typeahead orderType form-control" type="text" id="allOrderType" aria-describedby="Incomplete Orders" placeholder="Incomplete Orders">
</div>
这是我的JavaScript,用于附加到ID quantityReceived
console.log(a)
document.getElementById("quantityReceived").appendChild(a);
元素a
是这样的元素的组合,我可以在Google控制台中看到它。
<div id="autocomplete-list" class="auocomplete-items>
<div>
"Main"
<input type="hidden" value="main">
</div>
<div>
"Sub"
<input type="hidden" value="Sub">
</div>
</div>
但是,当我检查ID为quantityReceived
的父div时,看不到子元素a被追加。我不确定为什么会这样
答案 0 :(得分:0)
您尝试添加的html不正确。
您需要关闭输入,所以它应该像这样:
<div id="autocomplete-list" class="auocomplete-items>
<div>
"Main"
<input type="hidden" value="main"/>
</div>
<div>
"Sub"
<input type="hidden" value="Sub"/>
</div>
</div>
然后您可以检查结果
console.log(document.getElementById("quantityReceived"));
答案 1 :(得分:0)
乍看之下,由于您的示例缺少详细信息,因此只能猜测一下,但是我猜想a
实际上并不是可以正确附加的东西。因此,作为一种概念证明,也许可以在您遇到的问题时向您触发一个灯泡;
const child = document.createElement('aside');
document.getElementById('test1').appendChild(child);
div {
height: 5rem;
width: 10rem;
border: red 1px dashed;
padding: .5rem;
margin: 1rem auto;
}
div aside {
height: 1rem;
width: 3rem;
border: green 3px dotted;
padding: .5rem;
margin: 0 auto;
}
<div id="test1"></div>
答案 2 :(得分:0)
除了您要添加的HTML无效之外,我认为应该没有问题(如果HTML实际上是DOM节点而不是字符串!),请参见:
let a = document.createElement('div');
a.setAttribute('class', 'autocomplete-items');
a.setAttribute('id', 'autocomplete-list');
a.innerHTML = `
<div>
Main
<input type="hidden" value="main" />
</div>
<div>
Sub
<input type="hidden" value="sub" />
</div>
`;
document.getElementById("quantityReceived").appendChild(a);
<div class="d-flex quantityReceived" id="quantityReceived">
<button type="button" class="btn btn-info changeValue" onclick="allOrderType()">
<div id="spinner">
<i class="fas fa-caret-down"></i>
</div>
</button>
<input name="order" class="typeahead orderType form-control" type="text" id="allOrderType" aria-describedby="Incomplete Orders" placeholder="Incomplete Orders" />
</div>