Selector


Posted by mijouhsieh on 2023-03-02

CODEPEN LINK

1. node有2個class name

當node有2個class name時,selector括號內 2個class name中間不可有空格
即同時有2個class name,若有空格則分別為父層和子層的class name,結構不對。
<ul class="list-unstyled small"></ul>
const ul = document.querySelector('.list-unstyled.small')

2. node有2個class name

<ul>
    <li> a </li>
    <li> b </li>
    <li> c </li>
</ul>
錯誤寫法
document.querySelectorAll('ul').children

正確寫法
document.querySelector('ul').children
// HTMLCollection(3)[li, li, li]

正確寫法
document.querySelectorAll("ul li")
//NodeList(3) [li, li, li]

3. 修改 <img> 圖片來源

先抓node,再以node.src屬性="...." 重新賦值
若把屬性一開始寫入變數 let ul = document.querySelector('.list-unstyled.small').src 會無法賦值

另一種 新網址放變數newImg
node.setAttribute('src', newImg)

MDN Element.setAttribute()

setAttribute(name, value)

設定指定元素上的某個屬性。若屬性已存在,則更新該值;
否則,使用指定的 name 和 value 添加一個新的屬性。


#selectors #img src







Related Posts

F2E合作社|共用項目margin與padding|Bootstrap 5網頁框架開發入門

F2E合作社|共用項目margin與padding|Bootstrap 5網頁框架開發入門

側邊選單

側邊選單

婚姻匹配問題(Stable Marriage Problem)

婚姻匹配問題(Stable Marriage Problem)


Comments