Remember all the DOM changes you made over the years

⭐️ more front-end technology and knowledge, search subscription number JS bacteria subscription

Frameworks are used a lot. Do you remember the pure JS syntax for manipulating the DOM? Check out this article for a refresher ~ 🤔

Operating the className

addClass

To add class to an element, use the classList attribute, which returns a DOMTokenList object. The object has an add method to add class. If it does not have this attribute, use the className to concatenate the string

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

hasClass

Check whether a class exists

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

removeClass

Deletes a class of the element

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
    }
}
Copy the code

toggleClass

Toggle sets or unsets the class depending on the situation

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}`}}}Copy the code

The attributes and values of the element

attr

Get the attributes of the HTML element using getAttribute

el.getAttribute(attrName)

Use setAttribute to set the attributes of an HTML element

el.setAttribute(attrName, attrValue)

Remove attributes of HTML elements using removeAttribute

el.removeAttribute(attrName)

html

Get the element HTML code; Pass true to get outerHTML

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

OuterHTML or innerHTML overwrites the previous value

outerHTML/innerHTML = newHTMLString

text

Get the element contentText, consider compatibility innerText

el.contentText || el.innerText

Override the previous value with a contentText or innerText assignment

el.contentText/innerText = newVal

parse

Parse the HTML string and create a document-fragment using the createContextualFragment method

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

Operates the parent-child node

parent

Get the parent element

el.parentNode

closest

Starting with el, we get the ancestor of the first matched selector (including itself) from the inside out, using matches, which takes care of compatibility

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)
    }
}
Copy the code

appendChild

Append a new element to the element directly using the appendChild method

function appendChild(parentNode, newEl) {
    parentNode.appendChild(newEl)
}
Copy the code

insertBefore

To insert a new element before the element, use insertBefore. Note that this is called on parentNode, where refEl represents the reference node

function insertBefore(parentNode, newEl, refEl) {
    parentNode.insertBefore(newEl, refEl)
}
Copy the code

children

Gets all non-commented nodes under the element

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

Or use querySeclectorAll

removeChildren

Removes all child elements of the element

function remove(el) {
    el.firstChild && el.removeChild(el.firstChild) && remove(el)
}
Copy the code

hasChild

Check whether an element is contained under an element by passing in a Selector selector string or a node node

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

hasChildNodes

Checks if the element has child elements

parentNode.hasChildNodes

removeChild

Deletes the child element specified by the element

function removeChild(parentNode, childNode) {
    return parentNode.removeChild(childNode)
}
Copy the code

replaceChild

Replace one node with another

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

firstChild

Gets the first child node of the element

parentNode.firstChild

lastChild

Gets the first child node of the element

parentNode.lastChild

Operates the sibling node

elementSibling

To get the next or previous node whose nodeType is ELEMENT_NODE, using next/prevElementSibling compatibility requires a recursive call to 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)
        }
    }
}
Copy the code

siblings

Get all sibling nodes except yourself, including next/prev

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

insertAdjacentHTML

Append HTML code inside or outside an element. InsertAdjacentHTML takes two arguments, one relative location and one HTML string.

  • ‘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 -->Copy the code
function insertAdjacentHTML(el, pos, html) {
    el.insertAdjacentHTML(pos, html)
}
Copy the code

Node filtering and traversal

cloneNode

Clone node node, ifDeep pass whether deep clone

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

forEach

Gets a list of elements according to a CSS Selector and fires a callback function for each element

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

filter

Gets the element that matches the filter callback criteria according to Selector

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

matchSelector

Checks if the element is matched to an element selected by selector

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

Please pay attention to my subscription number, push technical articles about JS irregularly, only talk about technology not gossip 😊