還記得那些年你修改過的 DOM 嗎

20190421221922.png

整理常見 DOM 操做

⭐️ 更多前端技術和知識點,搜索訂閱號 JS 菌 訂閱

框架用多了,你還記得那些操做 DOM 的純 JS 語法嗎?看看這篇文章,來回顧一下~ 🤔css

操做 className

addClass

給元素增長 class,使用 classList 屬性,該屬性返回的是 DOMTokenList 對象,對象有一個 add 方法可添加 class,若是沒有這個屬性那麼使用 className 進行字符串拼接html

function addClass(el, className) {
    el.classList ? el.classList.add(className) : el.className += ` ${className}`
}

hasClass

檢查是否存在某個 class前端

function hasClass(el, className) {
    return el.classList ? el.classList.contains(className) : el.className.split(' ').includes(className)
}

removeClass

刪除元素的某個 classnode

function removeClass(el, className) {
    if (el.classList) {
        el.classList.remove(className)
    } else {
        const classList = el.className.split(' ')
        classList.splice(classList.indexOf(className), 1)
        el.className = classList
    }
}

toggleClass

toggle 根據狀況設置或取消設置 classweb

function toggleClass(el, className) {
    if (el.classList) {
        el.classList.toggle(className)
    } else {
        const classList = el.className.split(' ')
        if (classList.includes(className)) {
            classList.splice(classList.indexOf(className), 1)
            el.className = classList.join(' ')
        } else {
            el.className += ` ${className}`
        }
    }
}

元素的屬性和值

attr

經過 getAttribute 獲取 html 元素的屬性app

el.getAttribute(attrName)框架

經過 setAttribute 設置 html 元素的屬性ide

el.setAttribute(attrName, attrValue)函數

經過 removeAttribute 刪除 html 元素的屬性spa

el.removeAttribute(attrName)

html

獲取元素 html 代碼;傳入 true 獲取 outerHTML

function html(el, ifOuter = false) {
    return ifOuter ? el.outerHTML : el.innerHTML
}

經過 outerHTML 或 innerHTML 覆蓋以前的值

outerHTML/innerHTML = newHTMLString

text

獲取元素 contentText,考慮兼容性 innerText

el.contentText || el.innerText

經過 contentText 或 innerText 賦值覆蓋以前的值

el.contentText/innerText = newVal

parse

解析 HTML 字符串,使用 createContextualFragment 方法建立一個 document-fragment

function parse(htmlString) {
    const range = document.createRange()
    const parse = range.createContextualFragment.bind(range)
    return parse(htmlString)
}

操做父子關係節點

parent

獲取父元素

el.parentNode

closest

從 el 開始,從內到外,獲取第一個匹配 selector 的祖先元素(包括自身),使用 matches 方法,須要處理好兼容

function closest(el, selector) {
    const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector

    if (matchesSelector.call(el, selector)) {
        return el
    } else {
        el = el.parentElement
        return closest(el, selector)
    }
}

appendChild

在元素後追加新的元素,直接使用 appendChild 方法便可

function appendChild(parentNode, newEl) {
    parentNode.appendChild(newEl)
}

insertBefore

在元素前面插入新的元素,直接使用 insertBefore 便可,注意要在 parentNode 上調用,refEl 表明參照節點

function insertBefore(parentNode, newEl, refEl) {
    parentNode.insertBefore(newEl, refEl)
}

children

獲取元素下全部非註釋節點

function children(el) {
    return [...el.children].filter(item => item.nodeType != 8)
}

或使用 querySeclectorAll

removeChildren

刪除元素的全部子元素

function remove(el) {
    el.firstChild && el.removeChild(el.firstChild) && remove(el)
}

hasChild

檢查元素下是否包含某元素,可傳入 selector 選擇器字符串或 node 節點

function hasChild(el, child) {
    if (typeof child === 'string') {
        return el.querySelector(child) !== null
    } else {
        return el !== child && el.contains(child)
    }
}

hasChildNodes

檢查元素是否有子元素

parentNode.hasChildNodes

removeChild

刪除元素指定的子元素

function removeChild(parentNode, childNode) {
    return parentNode.removeChild(childNode)
}

replaceChild

使用一個節點替代另外一個節點

function replaceChild(parentNode, newNode, oldNode) {
    return parentNode.replaceChild(newNode, oldNode)
}

firstChild

獲取元素第一個子節點

parentNode.firstChild

lastChild

獲取元素第一個子節點

parentNode.lastChild

操做兄弟關係節點

elementSibling

獲取下一個或前一個 nodeType 爲 ELEMENT_NODE 的節點,使用 next/prevElementSibling 兼容性須要遞歸調用 next/prevSibling

function elementSibling(el, prev = false) {
    if (prev) {
        if (el.previousElementSibling) return el.previousElementSibling
        el = el.previousSibling
        if (el && el.nodeType === 1) {
            return el
        } else {
            return elementSibling(el, true)
        }
    } else {
        if (el.nextElementSibling) return el.nextElementSibling
        el = el.nextSibling
        if (el && el.nodeType === 1) {
            return el
        } else {
            return elementSibling(el)
        }
    }
}

siblings

獲取除了本身之外的全部 sibling 節點,包括 next/prev

function siblings(el) {
    return [...el.parentNode.children].filter(item => item !== el)
}

insertAdjacentHTML

在元素內部或外部追加 html 代碼;insertAdjacentHTML 接收兩個參數,一個是相對位置,一個是 html 字符串。

  • 'beforebegin': Before the element itself.
  • 'afterbegin': Just inside the element, before its first child.
  • 'beforeend': Just inside the element, after its last child.
  • 'afterend': After the element itself.
<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->
function insertAdjacentHTML(el, pos, html) {
    el.insertAdjacentHTML(pos, html)
}

節點過濾和遍歷

cloneNode

克隆 node 節點,ifDeep 傳入是否深度克隆

function cloneNode(el, ifDeep = true) {
    return el.cloneNode(ifDeep)
}

forEach

根據 css Selector 獲取元素列表並對每一個元素觸發回調函數

function forEach(selector, cb) {
    [...document.querySelectorAll(selector)].forEach(cb)
}

filter

根據 selector 獲取符合過濾回調函數條件的元素

function filter(selector, cb) {
    return [...document.querySelectorAll(selector)].filter(cb)
}

matchSelector

檢查元素是否與是 selector 選中的元素

function matchSelector(el, selector) {
    if (el.matches) {
        return el.matches(selector)
    } else {
        return [...el.parentNode.querySelectorAll(selector)].some(item => item === el)
    }
}

JS 菌公衆帳號

請關注個人訂閱號,不按期推送有關 JS 的技術文章,只談技術不談八卦 😊

相關文章
相關標籤/搜索