HTML页面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title></title> </head> <body> </body> </html>
1.在HTML中添加元素
<script> //append()创建一个列表 const ul=document.createElement("ul"); //循环来生成多个列表li for(let i=1;i<=5;i++){ const li=document.createElement("li"); li.textContent=`item${i}`; ul.append(li); } console.log(ul); </script>
2.插入在标签内部
li= document.createElement("li"); li.textContent="第一个元素"; ul.insertAdjacentElement("afterbegin",li); li= document.createElement("li"); li.textContent="最后一个元素"; ul.insertAdjacentElement("beforeend",li);
3.插入在标签外部
a=document.createElement("a"); a.innerText="《雪中悍刀行》"; a.href="http://www.baidu.com"; ul.insertAdjacentElement("beforebegin",a); a1=document.createElement("a"); a1.innerText="《剑来》"; a1.href="https://www.php.cn/"; ul.insertAdjacentElement("afterend",a1);
推荐:《2021年js面试题及答案(大汇总)》