还记得那些年你修改过的 DOM 吗

栏目: JavaScript · 发布时间: 6年前

内容简介::star:️ 更多前端技术和知识点,搜索订阅号框架用多了,你还记得那些操作 DOM 的纯 JS 语法吗?看看这篇文章,来回顾一下~

还记得那些年你修改过的 DOM 吗

整理常见 DOM 操作

:star:️ 更多前端技术和知识点,搜索订阅号 JS 菌 订阅

框架用多了,你还记得那些操作 DOM 的纯 JS 语法吗?看看这篇文章,来回顾一下~

操作 className

addClass

给元素增加 class,使用 classList 属性,该属性返回的是 DOMTokenList 对象,对象有一个 add 方法可添加 class,如果没有这个属性那么使用 className 进行字符串拼接

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

删除元素的某个 class

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 根据情况设置或取消设置 class

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 元素的属性

el.getAttribute(attrName)

通过 setAttribute 设置 html 元素的属性

el.setAttribute(attrName, attrValue)

通过 removeAttribute 删除 html 元素的属性

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

还记得那些年你修改过的 DOM 吗

请关注我的订阅号,不定期推送有关 JS 的技术文章,只谈技术不谈八卦 :blush:


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Hackers

Hackers

Steven Levy / O'Reilly Media / 2010-5-30 / USD 21.99

This 25th anniversary edition of Steven Levy's classic book traces the exploits of the computer revolution's original hackers -- those brilliant and eccentric nerds from the late 1950s through the ear......一起来看看 《Hackers》 这本书的介绍吧!

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具