JavaScript中的DOM简介及应用

来源:互联网 发布:英国 实力 知乎 编辑:程序博客网 时间:2024/06/06 02:37

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或mousedownfunction——事件触发后调用的函数useCapture——Boolean值,用于描述事件是冒泡还是捕获。
原创粉丝点击