javascript 关于dom节点操作的增删改查

dom节点的增删改查

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
  <title>dom-test</title>
  <style>
    .setColor{
      color: blue;
    }
    .setFtSz{
      font-size: 16px;
    }
  </style>
</head>
<body>
<div id="con">
  <p id="tlt">html dom操作 增 删 改 查</p>
  <p id="show">内容展示</p>
  <p id="showtest">测试用例</p>
</div>
<script type="text/javascript">
  let getDomById = document.getElementById('tlt')
  let getShowP = document.getElementById('show')
  let getDoms = document.getElementsByTagName('p')
  let getTestDom = document.getElementById('showtest')
  let pDom =getDomById.parentNode
  console.log(pDom)
  //
  // 1、创建元素 2、填充内容3、追加到已有元素中或body中
  let addNew = document.createElement('p')
  addNew.innerHTML = '我是新增的元素p'
  con.appendChild(addNew)
  let addNew2 = document.createElement('div')
  addNew2.innerHTML = '我是直接追加在body中的'
  document.body.appendChild(addNew2)

  //
  // 1、找需要删除的节点 2、需要删除节点父级 3、remove
  pDom.removeChild(getDomById)
  
  //
  // 1、修改元素内容
  getShowP.innerHTML = '我把原来内容改了'
  // 2、修改元素样式
  getShowP.style.color = '#f00'
  // 3、插入内容(insertBefore())/替换replaceChild()
  let addChildNew = document.createTextNode('子节点增加了内容')
  getShowP.appendChild(addChildNew)
  let reNew = document.createTextNode('我是来替换的')
  pDom.replaceChild(reNew, getShowP)
  //4、添加属性
  let addAtr = document.createAttribute('class')
  addAtr.value = 'setColor'
  getTestDom.setAttributeNode(addAtr)
  console.log(getTestDom.getAttribute('class')) // setColor
  getTestDom.setAttribute('class', 'setFtSz') // 更改属性值 指定的属性已存在,则仅设置/更改值。

  // 查 dom操作事件
  // getElementById
  // getElementsByTagName
  // getElementsByClassName
</script>
</body>
</html>

 

posted @ 2020-07-30 11:08  可可西里的骄傲  阅读(530)  评论(0编辑  收藏  举报