更新刪除DOM節點(重要)
阿新 • • 發佈:2022-03-29
更新節點
屬性用字串包
id1.innerText= ’123‘ ; //修改文字值
id1.innerHTML='<strong>123</strong>' //可以解析html文字標籤,加粗
id1.style.color='red' //可以操作css
id1.style.fontSize="39px"; //fontSize駝峰命名
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <div id="id1"> 9 10 </div> 11 <script> 12 var id1 = document.getElementById("id1"); 13 id1.innerText = 'abc'; 14 15 </script> 16 </body> 17 </html>
刪除節點
刪除節點步驟:先獲取父節點,再通過父節點刪除自己
father.removeChild(p1);
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <div id="father"> 9 <h1>標題</h1> 10 <p id="p1">p1</p> 11 <p class="p2">p2</p> 12 </div> 13 14 15 16 <script> 17 18 var self = document.getElementById("p1"); 19 var father = p1.parentElement; 20 father.removeChild(self); 21 22 //刪除是一個動態的過程 23 father.removeChild(father.children[0]); 24 father.removeChild(father.children[1]); 25 father.removeChild(father.children[2]);//這種刪除第一個元素後 索引改變 後面會報錯 26 </script> 27 28 </body> 29 30 31 </html>