您当前的位置: 首页 > 

彭世瑜

暂无认证

  • 2浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Dom基本操作之CURD

彭世瑜 发布时间:2020-04-21 16:40:13 ,浏览量:2

查找元素
id="box"
class="box"
name="box"
+ p > span
+ span
/**
 * 获取单个元素或多个元素(HTMLCollection)
 */
console.log(document.getElementById('box'));
console.log(document.getElementsByClassName('box'));
console.log(document.getElementsByTagName('div'));

/**
 * 类似jQuery方式
 * 获取单个元素 返回单个DOM元素,没有返回null
 */
console.log(document.querySelector('.box'));
console.log(document.querySelector('#box'));
console.log(document.querySelector('div'));
console.log(document.querySelector('[name="box"]'));
console.log(document.querySelector('div + p > span'));

/** 
 * 获取多个元素,返回NodeList, 转为数组
 */
const arr = [...document.querySelectorAll('div')]
console.log(arr);

// or
const alsoArr = Array.from(document.querySelectorAll('div'))
console.log(alsoArr);

// 链式操作
console.log(document.querySelector('p').querySelector('span'));

// 绑定 console中可以直接用$
const $ = document.querySelector.bind(document)
// console.log($('div'));

// 向上查找
console.log($('p > span').closest('p'));

添加 DOM 元素
首页

以前的方式

const link = document.createElement('a')
link.setAttribute('href', '/home')
link.className = 'active'
link.textContent = '首页'
 
// finally
document.body.appendChild(link)

jQuery

$('body').append('首页')

JavaScript

// 插入html
document.body.insertAdjacentHTML(
    'beforeend',
    '首页'
)

// 插入 HTML 元素
document.body.insertAdjacentElement(
    'beforeend',
    document.createElement('a')
)
 
// 插入文本
document.body.insertAdjacentText('afterbegin', 'cool!')

位置参数



    
  
     


移动 DOM 元素

  Title

 

  Subtitle

h2 移动到 h1 的后面去

const h1 = document.querySelector('h1')
const h2 = document.querySelector('h2')
 
h1.insertAdjacentElement('afterend', h2)
替换 DOM 元素
// 之前
parentNode.replaceChild(newNode, oldNode)

// 现在
oldElement.replaceWith(newElement)
移除 DOM 元素
// 之前
const target = document.querySelector('#target')
target.parentNode.removeChild(target)

// 现在
const target = document.querySelector('#target')
target.remove()
用 HTML 字符串创建 DOM 元素
const createSingleElement = (domString) => {
    const parser = new DOMParser()
  return parser.parseFromString(domString, 'text/html').body.firstChild
}
 
// usage
const element = createSingleElement('Home')

参考 DOM 高级工程师不完全指南

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.2271s