如何获取整个 HTML 下拉列表的值

我需要获取整个元素及其所有子元素的值,以便我可以创建该元素的副本。有没有办法用纯js来做到这一点?


<!DOCTYPE html><html>

<select id="select">

<option>Bulldog</option>

<option>Pitbull</option>

</select>

<!--The entire dropdown with all its child option elements should be duplicated into the div element:-->

<div id="div"></div>

</html>


幕布斯7119047
浏览 155回答 3
3回答

动漫人物

使用克隆节点:document.body.appendChild(document.querySelector('#select').cloneNode(true));它克隆该元素,然后将克隆附加到页面主体。您不需要获取元素的值。希望这个对你有帮助。

缥缈止盈

我认为最好给出每个选项的价值,也许这个js可以帮助你与 HTML<!DOCTYPE html><html><select id="select"><option value="Bulldog">Bulldog</option><option value="Pitbull">Pitbull</option></select><!--The entire dropdown with all its child option elements should be duplicated into the div element:--><div id="div"></div></html>和 JS :var j = document.getElementById("select");var i;var value = "List Value: ";for (i = 0; i < j.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; value = value + "\n" + j.options[i].text;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;console.log(value)

侃侃尔雅

下面的代码通过克隆整个元素并附加到元素 id="div" 来显示结果。让我知道这是否是您所需要的。<!DOCTYPE html><html>&nbsp; <body>&nbsp; &nbsp; <select id="select">&nbsp; &nbsp; &nbsp; <option>Bulldog</option>&nbsp; &nbsp; &nbsp; <option>Pitbull</option>&nbsp; &nbsp; </select>&nbsp; &nbsp; <!--The entire dropdown with all its child option elements should be duplicated into the div element:-->&nbsp; &nbsp; <div id="div"></div>&nbsp; </body></html><script>&nbsp; var x = document.querySelector("#select").cloneNode(true);&nbsp; document.getElementById("div").appendChild(x);</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript