4.前端筆記之jsdom基礎


一、簡介

文件對象模型(Document Object Model,簡稱DOM),是W3C組織推薦的處理可擴展標志語言的標准編程接口。DOM編程: DOM 是關於如何獲取、修改、添加或刪除 HTML 元素的標准。

HTML DOM 節點樹

通過 HTML DOM,樹中的所有節點均可通過 JavaScript 進行訪問。所有 HTML 元素(節點)均可被修改,也可以創建或刪除節點。

理解幾個概念,html標簽沒有父輩,沒有兄弟,所以html標簽為根標簽。head標簽是html子標簽,meta和title標簽之間是兄弟關系。如果把每個標簽當作一個節點的話,那么這些節點組合成了一棵節點樹。

二、選擇器(查找元素方法)

W3C提供了比較方便簡單的定位節點的方法和屬性,以便我們快速的對節點進行操作。分別為:getElementById()、getElementsByTagName()、getElementsByName()、getAttribute()、setAttribute()和removeAttribute()


1.getElementById()

getElementById()方法,接受一個參數:獲取元素的ID。如果找到相應的元素則返回該元素的HTMLDivElement對象,如果不存在,則返回null。

例:

<body>
<p id="demo">這是一個p標簽</p>

<script>
var x = document.getElementById('demo');
document.write('獲取標簽內容:'+ x.innerHTML+'</br>');
document.write('獲取標簽名:'+ x.tagName);

</script>
</body>

通過getElementById()獲取到特定元素節點時,這個節點對象就被我們獲取到了,而通過這個節點對象,我們可以訪問它的一系列屬性。

例如:

tagName	  獲取元素節點的標簽名
innerHTML 獲取元素節點里的內容
id		  獲取元素的id名稱
style	  CSS內聯樣式屬性值
className	CSS元素的類

document.getElementById('demo').id;	 //獲取id
document.getElementById('demo').id = 'person'; //設置id
document.getElementById('demo').style;	 //獲取CSSStyleDeclaration對象
document.getElementById('demo').style.color;	//獲取style對象中color的值
document.getElementById('demo').style.color = 'red';//設置style對象中color的值
document.getElementById('box').className;	//獲取class
document.getElementById('box').className = 'box';	//設置class	

2.getElementsByTagName()方法

可以獲取所有標簽元素

document.getElementsByTagName('*');	 //獲取所有元素
document.getElementsByTagName('li');		//獲取所有li元素,返回數組
document.getElementsByTagName('li')[0];		//獲取第一個li元素,HTMLLIElement
document.getElementsByTagName('li').item(0)	//獲取第一個li元素,HTMLLIElement
document.getElementsByTagName('li').length;	//獲取所有li元素的數目

案例:

<body>
	<a>我是一個a標簽</a>
	<p>我是一個p標簽</p>
	<li>我是li一號</li>
	<li>我是li二號</li>
<script>
var x = document.getElementsByTagName('a'); //獲取所有的a標簽元素返回數組
document.write(x[0].innerHTML + '</br>');     //輸出第一個a標簽的內容 #如果想輸出所有 可以for循環數組輸出
var i = document.getElementsByTagName('li');
for(var item in i){
    document.write('li的內容:'+ i[item].innerHTML +'</br>'); //循環輸出所有li標簽的內容
}
document.write('li的第一個內容:' + i[0].innerHTML);  //輸出第一個li標簽的內容
document.write('li標簽的數量'+ i.length);  //輸出li標簽的數量
</script>
</body>

3.getElementsByName()方法

getElementsByName()方法可以獲取相同名稱(name)的元素,返回一個對象數組HTMLCollection(NodeList)。

document.getElementsByName('add')			//獲取input元素
document.getElementsByName('add')[0].value	//獲取input元素的value值
document.getElementsByName('add')[0].checked	//獲取input元素的checked值

案例:

<body>
<p name="demo">我是一個小小的p標簽</p>
<script>
var x = document.getElementsByName('demo'); //獲取所有name=demo的標簽
x[0].style.color='red';  //將第一個name=demo的元素顏色改變 使用style屬性
document.write('內容:'+ x[0].innerHTML);		//輸出第一個name=demo的標簽內容
</script>						
</body>
//如果要輸出所有 可以使用for循環x數組。

4.getAttribute()方法

getAttribute()方法將獲取元素中某個屬性的值。它和直接使用.屬性獲取屬性值的方法有一定區別。

document.getElementById('box').getAttribute('id');//獲取元素的id值
document.getElementById('box').id;			//獲取元素的id值

document.getElementById('box').getAttribute('mydiv');//獲取元素的自定義屬性值
document.getElementById('box').mydiv		//獲取元素的自定義屬性值,非IE不支持

document.getElementById('box').getAttribute('class');//獲取元素的class值,IE不支持
document.getElementById('box').getAttribute('className');//非IE不支持

5.removeAttribute()方法

removeAttribute()可以移除HTML屬性。

document.getElementById('box').removeAttribute('style');//移除屬性

案例:

<body>
<div  id="add" style="color:red">我是一個帶顏色的div</div>
<button onclick="demo()">點擊取消字體顏色</button>
<script>
    function demo(){
    var x = document.getElementById('add');
    x.removeAttribute('style');
}

</script>
</body>

三、dom節點操作

1.node節點屬性

節點可以分為元素節點、屬性節點和文本節點,而這些節點又有三個非常有用的屬性,分別為:nodeName、nodeType和nodeValue。

元素:

<body>
<p id="demo">我是一個美麗的p標簽</p>
<script>
var x = document.getElementById('demo');
document.write('元素的標簽名'+x.nodeName+'</br>');   //類型是p標簽
document.write('元素的標簽類型'+x.nodeType+'</br>'); //類型是1
document.write('元素的值'+ x.nodeValue+'</br>');  //元素本身沒有內容所有是null
</script>			//如果要輸出內容 請使用innerHTML
</body>				//node只能獲取當前節點的內容

2.層次節點屬性

節點的層次結構可以划分為:父節點與子節點、兄弟節點這兩種。當我們獲取其中一個元素節點的時候,就可以使用層次節點屬性來獲取它相關層次的節點。

1).childNodes屬性

childeNodes屬性可以獲取某一個元素節點的所有子節點,這些子節點包含元素子節點和文本子節點。

<body>
<div id="demo"><p>我是一個p標簽</p><a>我是一個a標簽</a></div>
<script>
var x = document.getElementById('demo');
document.write(x.childNodes); //所有子節點列表 可以用for循環顯示
document.write(x.childNodes.length);//含有兩個子節點
document.write(x.childNodes[0].innerHTML); //輸出標簽內容
</script>
</body>

PS:使用childNodes[n]返回子節點對象的時候,有可能返回的是元素子節點,比如 HTMLElement;也有可能返回的是文本子節點,比如Text。元素子節點可以使用nodeName或者tagName獲取標簽名稱,而文本子節點可以使用nodeValue獲取。

for (var i = 0; i < demo.childNodes.length; i ++) {
//判斷是元素節點,輸出元素標簽名
	if (demo.childNodes[i].nodeType === 1) {
		alert('元素節點:' + demo.childNodes[i].nodeName);
//判斷是文本節點,輸出文本內容
	} else if (demo.childNodes[i].nodeType === 3) {
		alert('文本節點:' + demo.childNodes[i].nodeValue);
	}
}

PS:在獲取到文本節點的時候,是無法使用innerHTML這個屬性輸出文本內容的。這個非標准的屬性必須在獲取元素節點的時候,才能輸出里面包含的文本。

2.firstChild和lastChild屬性

firstChild用於獲取當前元素節點的第一個子節點,相當於childNodes[0];lastChild用於獲取當前元素節點的最后一個子節點,相當於childNodes[box.childNodes.length - 1]。

<body>
<div id="demo"><p>我是一個p標簽</p><p>我是一個a標簽</p></div>
<script>
var x = document.getElementById('demo');
document.write('第一個子節點'+x.firstChild);
document.write('最后一個子節點'+ x.lastChild);
</script>
</body>

3.ownerDocument屬性

ownerDocument屬性返回該節點的文檔對象根節點,返回的對象相當於document。

alert(box.ownerDocument === document);		//true,根節點

4.parentNode、previousSibling、nextSibling屬性
parentNode屬性返回該節點的父節點,previousSibling屬性返回該節點的前一個同級節點,nextSibling屬性返回該節點的后一個同級節點。

alert(box.parentNode.nodeName);				//獲取父節點的標簽名
alert(box.lastChild.previousSibling);			//獲取前一個同級節點
alert(box.firstChild.nextSibling);				//獲取后一個同級節點

5.attributes屬性

attributes屬性返回該節點的屬性節點集合。

document.getElementById('box').attributes		//NamedNodeMap
document.getElementById('box').attributes.length;//返回屬性節點個數
document.getElementById('box').attributes[0];	//Attr,返回最后一個屬性節點
document.getElementById('box').attributes[0].nodeType;	//2,節點類型
document.getElementById('box').attributes[0].nodeValue;	//屬性值
document.getElementById('box').attributes['id'];	//Attr,返回屬性為id的節點
document.getElementById('box').attributes.getNamedItem('id');	//Attr

四.節點操作

DOM不單單可以查找節點,也可以創建節點、復制節點、插入節點、刪除節點和替換節點。

1.write()方法

write()方法可以把任意字符串插入到文檔中去。

document.write('<p>我是一個p標簽</p>')'	;	//輸出任意字符串
可以覆蓋掉整個html頁面

2.createElement()方法

createElement()方法可以創建一個元素節點。

document.createElement('p');					//創建一個元素節點
//只是在內存中,並沒有真正的在頁面上顯示

3.appendChild()方法

appendChild()方法講一個新節點添加到某個節點的子節點列表的末尾上。

var x = document.getElementById('demo');		//獲取某一個元素節點
var p = document.createElement('p');			//創建一個新元素節點<p>
x.appendChild(p);						//把新元素節點<p>添加子節點末

4.createTextNode()方法

createTextNode()方法創建一個文本節點。

var text = document.createTextNode('我是文本節點');		//創建一個文本節點
p.appendChild(text);						//將文本節點添加到p里面

5.insertBefore()方法

insertBefore()方法可以把節點創建到指定節點的前面。

demo.parentNode.insertBefore(p, demo);			//把<div>之前創建一個節點

6.repalceChild()方法

replaceChild()方法可以把節點替換成指定的節點。

demo.parentNode.replaceChild(p,demo);			//把<div>換成了<p>

7.cloneNode()方法

cloneNode()方法可以把子節點復制出來。

	var x = document.getElementById('demo');		
	var clone = x.firstChild.cloneNode(true);		//獲取第一個子節點,true表示復制內容
	x.appendChild(clone);						//添加到子節點列表末尾

8.removeChild()方法

removeChild()方法可以把

demo.parentNode.removeChild(demo);			//刪除指定節點

案例:

<body>
<div id="container"></div>
<a href="http://www.liuyao.me" onclick="return AddElement();">添加</a>
<script>
function AddElement(){
    //創建標簽,添加至container中
    var createObj = document.createElement('a');
    createObj.href = 'http://www.liuyao.me';
    createObj.innerText = '耀耀博客';
    var nid =  document.getElementById('container');
    nid.innerHTML = createObj;
    nid.appendChild(createObj);
    return false;

}
</script>
</body>

五、操作樣式

改變 HTML 內容
改變 CSS 樣式
改變 HTML 屬性
創建新的 HTML 元素
刪除已有的 HTML 元素
改變事件(處理程序)

1.innerHTML方法

獲取元素內容和改變元素內容

<body>
<p id="demo">我是一個p標簽</p>
<script>
	var x = document.getElementById('demo');
    document.write(x.innerHTML); //顯示元素內容
    x.innerHTML='我改變了'; //改變元素內容
</script>
</body>


//點擊加1

<body>
<p id = 'num'>1</p>
<input  type="button" onclick="add()"/>
<script>
function add() {
    var nid = document.getElementById('num');
    var text = nid.innerHTML;
    text = parseInt(text);
    text += 1;
    nid.innerText = text;
}
</script>
</body>

2.改變樣式

<body>
<div id="demo" style="width: 100px;height: 100px;background: red;">我是紅色</div>
<button onclick="add()">點擊我改變顏色</button>
<script>
function add(){
    var x = document.getElementById('demo');
        x.style.background = 'blue';
}
</script>
</body>

六、事件

在元素上點擊或者其他操作
加載頁面
改變輸入字段

1.點擊改變背景顏色

<body>
<button onclick="demo()">點擊改變背景顏色</button>
<script>
function demo(){
    var x = document.body;
    x.style.background = 'red';
}
</script>
</body>

2.點擊改變文本內容

<body>
<p id="demo">我是一個文本內容</p>
<button onclick="add()">點擊改變文本內容</button>
<script>
function add(){
    var x = document.getElementById('demo');
    x.innerHTML = '被改變了';
}
</script>
</body>

3.用戶注冊提交

<body>
<form>
用戶名:<input  id="user" type="text"/>
密碼:<input  id="passwd" type="password"/>
<input  onclick="login()" type="submit" value="提交"/>
</form>
<script>
function login(){
    var x = document.getElementById('user').value;
    if(x ==''){
        alert('用戶名不能為空');
    }
    var y = document.getElementById('passwd').value;
    if(y == ''){
        alert('密碼不能為空');
    }
}
</script>
</body>

4.提交

<body>
<form id="from1" action="https://www.sogou.com/web" method="get">
<input name="query" type="text"/>
<div onclick="Submit()">提交</div>
</form>
<script>
function Submit(){
    document.getElementById('from1').submit();
}
</script>
</body>

5.搜索功能

<body>
<form id="from1" action="https://www.sogou.com/web" method="get">
<input name="query" type="text"/>
<input type="submit" onclick="return MySubmit();" value="提交"/>
</form>
<script>>
function MySubmit(){
    var q = document.getElementsByName('query')[0];
    if(q.value.trim()){
        return true;
    }else{
        alert('請輸入內容');
        return false;
    }

}
</script>
</from>
</body>

事件的基本用法:

1.onchange 事件

onchange 事件常結合對輸入字段的驗證來使用。

小寫轉大寫輸入:

<body>
請輸入:<input id="demo" onchange="add()" type="text"/>
<script>
function add(){
    var x=document.getElementById("demo");
    x.value=x.value.toUpperCase();
}
</script>
</body>

2.onmouseover 和 onmouseout 事件

onmouseover 和 onmouseout 事件可用於在用戶的鼠標移至 HTML 元素上方或移出元素時觸發函數。

//觸摸改變背景顏色
<body>
<div id="demo" onmouseover="adder()" onmouseout="addout()" style="width: 100px; height:100px; background: darkred">別碰我</div>
<script>
function adder(){
    var x = document.getElementById('demo');
    x.style.background = 'blue';
}
function addout(){
    var x =document.getElementById('demo');
    x.style.background = 'red';
}
</script>
</body>

//觸摸改變字體顏色
<body>
<p onmouseover="style.color='red'" onmouseout="style.color='blue'">碰我顏色就改變了</p>
</body>

3.onmousedown、onmouseup 以及 onclick 事件

onmousedown, onmouseup 以及 onclick 構成了鼠標點擊事件的所有部分。
首先當點擊鼠標按鈕時,會觸發 onmousedown 事件,
當釋放鼠標按鈕時,會觸發 onmouseup 事件,
最后,當完成鼠標點擊時,會觸發 onclick 事件。

<body>
<div id="demo" onmousedown="adddown()" onmouseup="addseup()" style="width: 100px; height:100px; background: darkred">我是一個div</div>
<script>
function adddown(){
    var x = document.getElementById('demo');
    x.style.background = 'blue';
}
function addseup(){
    var x = document.getElementById('demo');
    x.style.background = 'red';
}
</script>
</body>

window

window.onload = function(){}

    //jQuery:$(document).ready(function(){})
    //onload是所有DOM元素創建、圖片加載完畢后才觸發的。
	而ready則是DOM元素創建完畢后觸發的,不等圖片加載完畢。
	圖片還么有渲染,就可以進行事件的執行。

跑馬燈:

<body>
<input type="button" onclick="StopInterval();" value="停下來"/>
<script>
//    setInterval( '操作','間隔');
//    setInterval('alert('123')',2000)
//在title滾動
  obj1 = setInterval('Func()',1000);
//第二種 執行指定次數結束
//  obj1 = setTimeout('Func()',1000);
function StopInterval(){
    //清除定時器
//        clearInterval(obj1);
    clearTimeout(obj1);
}
function Func(){
    var text = document.title;
    var firstChar = text.charAt(0);
    var subText = text.substring(1,text.length);
    var newTitile = subText + firstChar;
    document.title = newTitile;
}
</script>
</body>	

使用焦點

<body>
<a id="mefunc" href="http://www.liuyao.me" >我是劉耀</a>
<br/>
<input type="button" onclick="getfocus()" value="獲得焦點">
<input type="button" onclick="losefocus()" value="失去焦點">
<script>
function getfocus()
{document.getElementById('mefunc').focus()}

function losefocus()
{document.getElementById('mefunc').blur()}
</script>
</body>

關於Document對象的用法

1.輸出文本

<body>
<script>
document.write('我是劉耀');
</script>
</body>

2.輸出html

<body>
<script>
document.write('<h1>我是劉耀</h1>');
</script>
</body>

3.輸出頁面標題

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>我是一個標題</title>
</head>
<body>
<script>
document.write(document.title);
</script>
</body>
</html>

4.輸出當前頁面URL

<body>
<script>
document.write(document.URL);
</script>
</body>

5.獲取表單數

<body>

<form name="Form1"></form>
<form name="Form2"></form>
<form name="Form3"></form>
<script>
document.write("文檔包含: " + document.forms.length + " 個表單。")
</script>
</body>
</html>

關於dom在表單中的用法:

1.選擇復選框和取消復選框
<body>
<form>
<input type="checkbox" id="myCheck" />
<input type="button" onclick="check()" value="選定" />
<input type="button" onclick="uncheck()" value="取消選定" />
</form>
<script>
function check()
{
    document.getElementById("myCheck").checked=true
}

function uncheck()
{
    document.getElementById("myCheck").checked=false
}
</script>
</body>

2.重置表單
<body>
<form id="demo">	
用戶名:<input type="text"/>
密碼:<input type="password" />
<button onclick="add()">重置</button>
</form>
<script>
function add(){
    var x = document.getElementById('demo');
    x.reset();
}
</script>
</body>
3.提交
<body>
<form id="demo" action="www.baidu.com" method="get" >
用戶名:<input type="text"/>
密碼:<input type="password" />
<button onclick="add()">提交</button>
</form>
<script>
var x = document.getElementById('demo');
x.submit()
</script>
</body>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM