js DOM操作

2017-07-22  本文已影响0人  _YDS

1.认识DOM

在网页正常加载的时候,浏览器会创建页面的文档对象类型(Document Object Model)

2.查询元素

 var el1=document.querySelector(".kk");
 var el2=document.querySelector('#id>.kk');
 querySelector无法选中css的伪类.括号内单双引都可
var maths=document.querySelectorAll("div.kk,div.alert");
这段代码返回Clss属性是kk和alert的div元素

3.DOM修改添加

(1)修改html内容

(2)修改html属性

![](smiley.gif)
<script>
    document.getElementById("image").src="landscape.jpg";
    document.getElementById("image").setAttribute('src','landscape.jpg');
</script>

(3)改变样式

document.element.style.xxx=xxx

<p id="p1">我是段落,要变色</p>
<button>变色</button>
<script>
    document.getElementsByTagName('button')[0].onclick=function(){
        document.getElementById('p1').style.color="red";
    }
</script>

(4)创建新的html元素

创建元素,然后追加到已有的元素上

<div class="d1"></div>
<script>
    var para=document.createElement("p");
    para.innerHtml="我是新添加的段落";
    var element=document.getElementById("d1");
    element.appendChild(para);//加在最后面
    element.firstChild(para);//加在第一个
</script>
上一篇 下一篇

猜你喜欢

热点阅读