JS 添加DOM元素 删除DOM元素
创建一个DOM对象
1
| document.createElement("标签名");
|
DOM对象添加一个子DOM
1
| dom.appendChild(subDOM);
|
例如:
1 2 3 4 5 6 7
| function add() { var bodyDom = document.body; var inputText = document.createElement("input"); inputText.value = '内容'; inputText.id = 'generatedDom'; bodyDom.appendChild(inputText); }
|
DOM删除一个子DOM
格式:
1
| dom.removeChild(subDom);
|
例如:
1 2 3 4 5
| function remove() { var bodyDom = document.body; var inputText = document.getElementById("generatedDom"); bodyDom.removeChild(inputText); }
|
JS 复制到系统剪贴板
1 2 3 4 5 6 7 8 9
| function copy(text) { var temp = document.createElement("textarea"); temp.value = text; document.body.appendChild(temp); temp.select(); alert('打断,看效果'); document.execCommand('copy'); document.body.removeChild(temp); }
|
完整例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| <html>
<head> <meta charset="utf-8"> <style type="text/css"> </style> <script> function add() { var bodyDom = document.body; var inputText = document.createElement("input"); inputText.value = '内容'; inputText.id = 'generatedDom'; bodyDom.appendChild(inputText); }
function remove() { var bodyDom = document.body; var inputText = document.getElementById("generatedDom"); bodyDom.removeChild(inputText); }
function copy(text) { var temp = document.createElement("textarea"); temp.value = text; document.body.appendChild(temp); temp.select(); alert('打断,看效果'); document.execCommand('copy'); document.body.removeChild(temp); } </script> </head>
<body> <textarea cols="100" rows="10" style="display: block;"></textarea> <button onclick="add()">添加元素</button> <button onclick="remove()">移除元素</button> <button onclick="copy('通过复制的到的内容')">复制元素</button> </body>
</html>
|