Do you remember the DOM you modified in those years?

Keywords: Javascript Fragment Attribute

Organize common DOM operations

More Front-end Technology and Knowledge Points, Search for Subscription Number JS Bacteria Subscription

Framework is used a lot. Do you remember those pure JS grammars that operate on DOM? Look at this article and review it.

Operating className

addClass

To add class to the element, use the classList attribute, which returns the DOMTokenList object. The object has an add method to add class. If not, use className for string splicing.

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

hasClass

Check for the existence of a class

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

removeClass

Delete a class of elements

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 sets or cancels class as appropriate

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}`
        }
    }
}

Attributes and values of elements

attr

Getting attributes of html elements through getAttribute

el.getAttribute(attrName)

Setting attributes of html elements through setAttribute

el.setAttribute(attrName, attrValue)

Delete attributes of html elements by removeAttribute

el.removeAttribute(attrName)

html

Get the element html code; pass in true to get outerHTML

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

Override previous values through outerHTML or innerHTML

outerHTML/innerHTML = newHTMLString

text

Get the element contentText, considering compatibility innerText

el.contentText || el.innerText

Override previous values by contentText or innerText assignments

el.contentText/innerText = newVal

parse

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

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

Operating parent-child relationship nodes

parent

Get the parent element

el.parentNode

closest

Starting from el, from inside to outside, get the first ancestor element (including itself) that matches selector. Using matches method, compatibility needs to be handled well.

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

Add a new element after the element and use the appendChild method directly.

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

insertBefore

Insert a new element in front of the element and use insertBefore directly. Note that you need to call it on parentNode. refEl represents the reference node.

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

children

Get all non-annotated nodes under the element

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

Or use query Seclector All

removeChildren

Delete all child elements of an element

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

hasChild

Check whether an element is included under the element, and pass in the selector selector string or node

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

hasChildNodes

Check whether the element has child elements

parentNode.hasChildNodes

removeChild

Delete the child elements specified by the element

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

replaceChild

Replace one node with another

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

firstChild

Get the first child node of the element

parentNode.firstChild

lastChild

Get the first child node of the element

parentNode.lastChild

Operating Brotherhood Nodes

elementSibling

Get a node whose next or previous nodeType is ELEMENT_NODE and recursively call next/prevElementSibling using next/prevElementSibling compatibility

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

Get all sibling nodes except yourself, including next/prev

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

insertAdjacentHTML

Add html code inside or outside the element; insert Adjacent html receives two parameters, one is the relative position, and the other is the 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 -->
function insertAdjacentHTML(el, pos, html) {
    el.insertAdjacentHTML(pos, html)
}

Node filtering and traversal

cloneNode

Cloning node, if Deep afferent is deep cloning

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

forEach

Get the list of elements according to css Selector and trigger callback functions for each element

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

filter

Obtaining elements that meet the filter callback function conditions according to selector

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

matchSelector

Check whether the element is the element selected by the selector

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

Please pay attention to my subscription number, push technical articles about JS from time to time, and only talk about technology, not gossip (1)

Posted by dabas on Mon, 06 May 2019 19:15:39 -0700