JavaScript-屬性的增加,刪除,更改,查詢

查詢屬性值用getAttribute()方法

<body>

讀取 <a href="dom_obj_attributes.php" target="_blank">Attr 對象</a>.
<p id="demo">單擊按鈕以顯示上述鏈接的目標屬性的值</p>
<button onclick="myFunction()">點我</button>
<script>
function myFunction(){
	var a=document.getElementsByTagName("a")[0];
	document.getElementById("demo").innerHTML=a.getAttribute("target");
}
</script>

點擊按鈕時,將獲取屬性target的值:_blank替換掉P標籤中的內容。

 

增加屬性值用setAttribute()方法

<input value="OK">

<p id="demo">點擊下面的按鈕來設置按鈕的類型屬性。</p>
<button onclick="myFunction()">點我</button>
<script>
function myFunction(){
	document.getElementsByTagName("INPUT")[0].setAttribute("type","button"); 
};
</script>

點擊按鈕後,將input的type值設置爲button,input輸入框就會變爲button按鈕。

 

刪除元素值用removeAttribute()方法

<h1 style="color:red">Hello World</h1>
<p id="demo">點擊下面的按鈕刪除上面的標題的樣式屬性</p>
<button onclick="myFunction()">點我</button>
<script>
function myFunction(){
	document.getElementsByTagName("H1")[0].removeAttribute("style"); 
};

</script>

點擊按鈕後,刪除h1標籤的style屬性,字體顏色從紅色變爲默認黑色。

 

查詢元素值用attributes方法

<p id="demo">單擊按鈕,查看按鈕元素有多少個屬性:</p>
<button onclick="myFunction()">點我</button>
<script>
function myFunction(){
	var btn=document.getElementsByTagName("BUTTON")[0];
	var x=document.getElementById("demo");  
	x.innerHTML=btn.attributes.length;
}
</script>
<p>結果應爲1(按鈕元件的onclick屬性)</p>
<p><strong>注意:</strong> 在Internet Explorer 8 或者更早版本中,attributes 屬性將返回所有可能元素的集合 ,並將在這個示例中顯示一個比1更高的數字。</p>

attributes 屬性返回指定節點屬性的集合,可以使用 length 屬性確定屬性的數量,然後你可以遍歷所有的屬性節點提取你想要的信息。

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