JS: day03

2017-08-02  本文已影响0人  AnnQi

一、DOM(文档对象模型)

DOM对象方法.png

1、nodeValue 属性(规定节点的值)

①元素节点的 nodeValue 是 undefined 或 null
②属性节点的 nodeValue 是属性值
③文本节点的 nodeValue 是文本本身

<p id="test">hello world</p>
<script>
    var test = document.getElementById("test");
    console.log(test.firstChild.nodeValue);
</script>

2、nodeType 属性(返回节点的类型)

①元素(标签)节点返回的类型type------------1
②属性(ID)节点返回的类型type---------------2
③文本(文字)节点返回的类型type------------3

<p id="test">hello world</p>

<script>
    var p = document.getElementById("test");
    var attr=p.getAttributeNode("id");
    console.log(attr.nodeType);
</script>

3、获取元素的值(childNodes)

<p id="text">
         我是谁
         <a href="">hello</a>
          good
  </p>

<script>
//    .firstChild 获取第一个节点
//    .firstElementChild  获取第一个元素节点
//    .lastChild  获取最后一个节点
//    .lastElementChild  获取最后一个元素节点
    var p=document.getElementById("text");
    console.log(p.childNodes[0].nodeType);
</script>

4、创建新的 HTML 元素(createElement / createTextNode / appendChild)

<div id="parent">
    good
</div>

<script>
    var parent = document.getElementById("parent");
    var p = document.createElement("p");
    var text = document.createTextNode("hello world");
    p.appendChild(text);
    console.log(p);
    parent.appendChild(p);
</script>

5、添加新的 HTML 元素 - insertBefore(新的节点newChild,参照节点refChild)

如果要添加HTML 元素,必须清楚该元素的父元素:(this.parentNode:当前对象的父节点)

<div id="div">
    <p>first</p>
    <!--<p>hello world</p>-->
    <p id="one">good</p>
</div>

<script>
    var div = document.getElementById("div");
    var one = document.getElementById("one");
    /*1.生成p标签*/
    var p = document.createElement("p");
    var txt = document.createTextNode("hello world");
    p.appendChild(txt);
    console.log(p);
    div.insertBefore(p,one)
</script>

6、删除已有的 HTML 元素(removeChild)

如果要删除 HTML 元素,必须清楚该元素的父元素:(this.parentNode:当前对象的父节点)

<p>hello world</p>
<p id="del">删除我</p>
<button id="btn">btn</button>

<script>
    var btn = document.getElementById("btn");
    var del = document.getElementById("del");
    btn.onclick = function(){
            this.parentNode.removeChild(del);
    };
</script>

7、替换 HTML 元素(replaceChild)

如果要替换 HTML 元素,必须清楚该元素的父元素:(this.parentNode:当前对象的父节点)

<p>hello world</p>
<a id="one" href="#">baidu</a> <br/>
<!--<span>我替换你</span>-->
<button id="btn">btn</button>

<script>
    var btn = document.getElementById("btn");
    var span = document.createElement("span");
    var txt = document.createTextNode("我替换你");
    var one = document.getElementById("one");
    span.appendChild(txt);
    btn.onclick=function(){
        this.parentNode.replaceChild(span,one);
    }
</script>
上一篇 下一篇

猜你喜欢

热点阅读