HTML DOM setAttribute()、與createAttribute()


setAttribute()、與createAttribute() 都可以動態的為DOM 添加屬性;但是用法卻不一樣;

 

1、setAttribute()

setAttribute() 直接在DOM節點上添加屬性:

語法:

element.setAttribute(attributename,attributevalue)

例子:

<p >
    <span>1</span>,
    <span>2</span>
    <span>3</span>
    <span>4</span>
    <span>5</span>
</p>

在<p>節點上添加title屬性:

var p=document.getElementsByTagName('p')[0];
p.setAttribute('title','one to five');

2、createAttribute()用法相對復雜一點;

語法:

element.setAttributeNode(attributenode)
var ti=document.createAttribute('title');//創建獨立的屬性節點
ti.nodeValue='one to five';//設置屬性節點值
var p=document.getElementsByTagName('p')[0];
p.setAttributeNode(ti)
//追加的設置屬性節點

可以看出,createAttribute(),與setAttributeNode()是在一起使用的,與createTextNode(),createElement() 類似;先獨立的創建文本節點、屬性節點或元素節點。然后再追加到已有的文檔節點后面;不同的是追加文本節點和元素節點使用appendChild()方法;追加屬性節點使用setAttributeNode()方法。

直接使用setAttribute()要方便的多。

 


免責聲明!

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



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