HTML content is empty
<!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>php.cn</title> </head> <body> </body> </html>
1. Create DOM element
<script> const ul=document.createElement("ul"); </script>
2. Add content to the DOM
<span style="font-size: 16px;">append()</span>
Insert the specified content at the end of the selected element
<script> const ul=document.createElement("ul"); for(let i=1;i<=5;i++){ const li=document.createElement("li"); li.textContent=`item${i}`; ul.append(li); } document.body.append(ul); </script>
<span style="font-size: 16px;">prepend()</span>
Add specified content to the head of the selected element
<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); //prepend()在头部添加li li=document.createElement("li"); li.textContent="first item"; li.style.color="red"; ul.prepend(li); document.body.append(ul); </script>
Recommended: "2021 js interview questions and answers (large summary)》
The above is the detailed content of How to add DOM elements in Javascript. For more information, please follow other related articles on the PHP Chinese website!