JavaScript中的DOM简介及应用

1.getAttribute()
通过元素节点的属性名称获取属性的值
setAttribute()
通过元素节点的属性名称设置属性的值
eg.

document.getElementsByTagName("a")[0].getAttribute("href")
document.getElementsByTagName("a")[0].setAttribute("href","http://www.hao123.com")

2.访问子节点

  • childNodes 子节点(包含空节点)
  • firstChild 第一个子节点(包含空节点)
  • lastChild 最后一个子节点(包含空节点)
  • Children 子节点(不包含空节点)
  • firstElementChild 不包空的第一个子节点
  • lastElementChild 不包含空的最后一个子节点
    eg.
alert(newp.childNodes.length)
alert(newp.children.length)
alert(newp.children[0].innerText)
alert(newp.firstElementChild.innerText)
alert(newp.lastChild.innerText)
alert(newp.parentNode.parentNode.nodeName)

3.访问父节点
parentNode 访问父节点,可嵌套使用去寻找父节点的父节点
offsetParent 访问有定位属性的父节点


4.兄弟节点

  • nextSibling 访问后一个兄弟节点(含空节点)
  • previousSibling 访问前一个兄弟节点(含空节点)
  • nextElementSibling 访问后一个兄弟节点(不含空节点)
  • previousElementSibling访问前一个兄弟节点(不含空节点)

eg.

alert(one.previousSibling.innerText)
alert(one.nextSibling.innerText)
alert(one.previousElementSibling.innerText)
alert(one.nextElementSibling.innerText)

5.插入节点
创建节点:
document.createTextNode(“ ”)创建文本节点
document.createElement(“ ”)创建元素节点
添加子节点:
appendChild()

eg.

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<ul>
    <li>1111</li>
    <li>2222</li>
    <li>3333</li>
</ul>

<script>
    var newli=document.createElement("li");
    var uls=document.getElementsByTagName("ul")[0];
    newli.className="one";
    newli.innerText="hello,world";
    uls.appendChild(newli)
</script>
</body>
</html>

这里写图片描述


6.删除节点
removeChild()


7.替换节点
replaceChild(新节点,旧节点)

用法: 父元素名.replaceChild(新节点,旧节点)

8.DOM EventListener事件监听
作用:可以给同一个事件绑定不同或相同的事件

用法:element.addEventListener(“event”,functionuseCapture);

event——事件类型,如click或mousedown
function——事件触发后调用的函数
useCapture——Boolean值,用于描述事件是冒泡还是捕获。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值