JS 之 DOM

87 阅读2分钟

JS 之 DOM

DOM就是文档对象模型的缩写 Document Object Model

我们可以把DOM看作一棵“树”,通过树的枝干来去访问节点树叶。

节点

  • 元素节点(element node) <p> <ul> <li>等标签
  • 文本节点(text node)

没有内容的文档是没有任何价值的,而大多数内容都是由文本提供

  • 属性节点(attribue node) 就是各个标签的属性什么类名啊颜色等等

常见的获取元素节点的方式

1.document.getElementById('要获取节点的Id名')

通过ID获取复合的节点,单个对象

2.document.getElementsByTagName('要获取节点的标签名')

通过标签名获取符合的节点,获取出来的是一个节点对象集合

3.document.getElementsByClass('要获取节点的类名')

通过类名获取符合的节点

获取属性和设置属性

    <p class=title'> hetao测试</p>
 #red{
 color:red;
 }

getAttribute() 获取

    var op = document.getElementsByTagName('p')[0];
    console.log(op);
    var cls = op.getAttribute('class')
    console.log(cls)
    

setAttribute()设置

op.setAttribute('id','red');//通过设置ID 来获取相应的样式

节点属性

DOM中,每一个节点都是一个对象。DOM节点有三个重要的属性:

  1. nodeName: 节点的名称
  2. nodeValue: 节点的值
  3. nodeType: 节点的类型
  • nodeName属性: 节点的名称,是只读
  1. 元素节点的nodeName与标签名相同
  2. 属性节点的nodeName与属性的名称相同
  3. 文本节点的nodeName永远是#text
  4. 文档节点的nodeName永远是#document
  5. 注释节点的nodeName永远是#comment
  • nodeValue属性: 节点的值
  1. 元素节点的nodeValue是 undefined 或 null
  2. 文本节点的nodeValue是文本自身
  3. 属性节点的nodeValue是属性的值
  • nodeType属性: 节点的类型,只读
元素类型节点类型
元素1
属性2
文本3
注释8

节点对象的常用属性

获取孩子节点

    var father = document.getElementById('father');
    console.log(father.childNodes); //获取所有孩子节点
    console.log(father.firstChild); //获取第一个孩子
    console.log(father.lastChild);  //获取最后一个孩子

获取父级节点

     var child = document.getElementById('child');
     console.log(child.parentNode);

获取兄弟节点

    var brother = document.getElementById('brother');
    console.log(brother.nextSibling); //下一个兄弟节点
    console.log(brother.previousSibling);//上一个兄弟节点

动态的操作节点

  1. 创建节点 createElement()
  2. 插入节点 appendChild() insertBefore(newNode,node)
  3. 删除节点 removeChild()
  4. 替换节点 replaceChild(newNode,node)
  5. 创建文本节点 createTextNode()

动态操作样式

    <p id='box' style="" >hetao</p>
    var op = document.getElementById('box');
    console.log(op.style);
    op.style.backgroundColor = 'black';
    op.style.color = 'white';
    op.style.width = '200px';
    op.style.height = '200px';

事件

  • onclick 鼠标点击事件
  • onmouseover 鼠标经过事件
  • onmouseout 鼠标移开事件
  • onchange 文本框内容改变事件
  • onselect 文本框内容被选中事件
  • onfocus 光标聚焦事件
  • onblur 光标失焦事件
  • onload 网页加载事件

onclick

    <div id='box' onclick="add();" >hetao</div>
    #box{
        width:200px;
        height:200px;
        background-color:red'
    }
    var box1 = document.getElementById('box');
    box1.onclick = function(){
        alert('点击事件触发')
    }
    
    function add(){
        alert('行内点击事件触发')
    }

onmouseover

    <div id='box' onclick="add();" >hetao</div>
    #box{
        width:200px;
        height:200px;
        background-color:red'
    }

onmouseout

    var box1 = document.getElementById('box');
    box1.onmouseover = function(){
        this.style.backgroundColor = 'blue'
    }
    box1.onmouseout = function(){
        this.style.backgroundColor = 'red'
    }