JS DOM

取得節點

  • 取得元素
格式 屬性 說明
物件 .getElementById() 取得該id的元素
陣列 .getElementsByClassName() 取得該class的所有元素
陣列 .getElementsByTagName 取得該標籤的所有元素
.querySelector() 取得該標籤該class的第一個元素
.querySelectorAll() 取得該標籤該class的所有元素

  • 取得元素的內容
// HTML
<p>段落<span>內文</span></p>

// JavaScript
let p_el = document.getElementsByTagName("p")[0];
Example Console
p_el.outerHTML <p>段落<span>內文</span></p>
p_el.innerHTML 段落<span>內文</span>
p_el.innerText 段落內文

  • 取得元素的屬性
// HTML
<p id="para" data-id="123">段落</p>

// JavaScript
let p_el = document.getElementById("para");
Example Console
p_el.getAttribute("data-id") 123
p_el.data-id 123

查找節點

層級 屬性 說明
找子層 .querySelector() 找子層第一個同名元素
找子層 .querySelectorAll() 找子層全部同名元素
找子層 .children 找子層(第一層)元素
找子層 .firstElementChild 找子層第一個元素
找子層 .lastElementChild 找子層最後一個元素
找同層 .previousElementSibling 找同層前一個元素
找同層 .nextElementSibling 找同層後一個元素
找父層 .parentElement 找父層(當前最近)元素
找父層 .closest() 找父層指定元素

更新節點

  • 方法一 .setAttribute("欲更新的屬性", "欲設定的值")
let para1 = document.getElementById("para");
para1.setAttribute("style", "color: red;");
  • 方法二 點語法
var btn1 = document.getElementById("btn");
btn1.addEventListener("click", function(){
    this.disabled = true;
});

新增節點

  • .insertAdjacentHTML("位置參數", "html字串")
    • 位置參數:afterend, beforeend, afterbegin, beforebegin
    • html字串:如<p>新段落(afterend)</p>

刪除節點

屬性 說明
.remove() 刪除元素節點
.removeAttribute("") 刪除元素的屬性

操控CSS屬性

  • .style的寫法
let the_block1 = document.getElementById("the_block");

the_block.style.opacity = 0.6;
the_block.style.backgroundColor = "red";

操控class

屬性 說明
.classList.add("") 將該元素加上指定class
.classList.remove("") 將該元素移除指定class
.classList.contains("") 判斷該元素是否存在指定class
.classList.toggle("") 檢查該元素是否具有指定class,若有,則移除;若無,則加上
tags: frontend jsnote :arrow_right: Back to Front End Homepage :arrow_left: