使用JavaScript操作Document對象

1.根據id值獲取Document對象

var id= document.getElementById("id");

2.獲取Document對象指定屬性
例如需要獲取標籤的name屬性

var name= child.getAttribute('name');

獲取標籤中的value值

var value= document.getElementById("id").value;

返回表格行的開始和結束標籤之間的 HTML

var value= document.getElementById("id").innerHTML;

3.獲取當前節點的父、子、同級節點
獲取父級節點

var id= document.getElementById("id");
var  parent = id.parentNode;

獲取子級節點

var id= document.getElementById("id");
var  Child= id.firstElementChild;

獲取同級節點

var id= document.getElementById("id");
var  Sibling= id.previousElementSibling;

4.創建html標籤並設置屬性值

var oTitle= document.createElement('div');	//創建div
oTitle.className = 'strNo';	//設置class屬性
oTitle.id= 'str';	//設置id屬性
var oSpan = document.createElement('span'); //創建span標籤
oSpan.innerHTML = 'hello word'; //設置標籤間內容
oTitle.appendChild(oSpan); //將span標籤設置成div的子節點

實際效果

<div id="str" class="strNo">
	<span>hello word</span>
</div>

5.操作CSS樣式(以上方div爲例)

var str= document.getElementById("str");
str.style.width = '100px';	//設置div寬度爲100像素
str.style.height = '100px';  //設置div高度爲100像素

獲取當前頁面可視區的高度、寬度

document.documentElement.clientHeight;
document.documentElement.clientWidth;

操作div居中

str.style.left = (document.documentElement.clientWidth - 100)/2 + 'px';	//設置div左側距離
str.style.top = (document.documentElement.clientHeight - 100)/2 + 'px';	//設置div上方距離

刪除div

document.body.removeChild(str);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章