JS選擇元素節點方法
使用基本指令選擇document.querySelector來選擇
HTML
1 | <body> |
選出class標籤為me的元素
1 | const me = document.querySelector('.me') |
parentElement
選擇me的父元素和選擇me的父元素的父元素
1 | me.parentElement // 會選擇到<div class=""father>...</div> |
children[i]
選擇me的第一個子元素和選擇me的第二個子元素
1 | me.children[0] // 會選擇到<div class="son1">son1</div> |
nextElementSibling & previousElementSibling
選擇me的下一個同層級元素,和選擇me的上一個同層級元素
1 | me.nextElementSibling // 會選擇到<div class="my-brother"> my-brother</div> |
firstElementChild, lastElementChild
選擇me的第一個子元素,選擇me的最後一個子元素
1 | me.firstElementChild // 會選擇到<div class="son1">son1</div> |
appendChild
Node.appendChild(sample)
是將一個節點加到指定的父節點下面所有子節點的最後面。
如果sample這個節點已經存在document樹當中,那 appendChild(sample) 會將原本sample這個節點位置移動到node這個新的位置(不需要事先移除要移動的節點)。
1 | // TodoList Delete and check |
利用matches或classList.contains來比對目標對象
.matches
target.matches(‘.class’或’#id’) 轉譯:目標對象元素是否含有.class或#id,回傳true或fals
1 | // 刪除函式 |
.classList.contains
或是也可以用
target.classList.contains(‘string’) 轉譯:目標對象元素class屬性裡是否含有’string’值,回傳true或fals
關於dataset
可以在元素標籤上設定data資料,在使用JS去取得點擊目標元素上的dataset資料
1 | <div id="user" data-id="1234567890" data-user="ac-genie" data-date-of-birth>AC Genie</div> |
然後我們可以呼叫 dataset. 來取得這些屬性的值,你會發現這些值的型態都是字串*:
1 | const el = document.querySelector('#user'); |
更改元素style
我們常用classList.add來增加元素的樣式或改變樣式,但若本身已經設定好樣式,只是要更改樣式其中的屬性的話可以使用下面此方法。
1 | const el = document.querySelector('#user'); |