HTML DOM Element setAttributeNode() 方法

定义和用法

setAttributeNode() 方法向元素中添加指定的属性节点,并返回 Attribute 对象。

如果这个指定的属性已存在,则此方法会替换它。

替代方案:

使用 setAttribute() 方法 更容易。

另请参阅:

参考手册:

getAttributeNode() 方法

removeAttributeNode() 方法

createAttribute() 方法

getAttribute() 方法

setAttribute() 方法

hasAttribute() 方法

Attribute value 属性

HTML DOM Attribute 对象

教程:

HTML پراپرٹی

setAttribute() 和 setAttributeNode() 的区别

setAttribute() 方法替换属性值。

setAttributeNode() 方法替换 Attribute 对象。

在将属性添加到元素之前,您必须创建 Attr 对象并设置 Attr 值。

结果将是相同的。

实例

例子 1

设置第一个 <h1> 元素的 class 属性节点:

const attr = document.createAttribute("class");
attr.value = "democlass";
const h1 = document.getElementsByTagName("H1")[0];
h1.setAttributeNode(attr);

ਸਵੈ ਦੀ ਜਾਂਚ ਕਰੋ

ਸੈਟ ਤੋਂ ਪਹਿਲਾਂ:

Hello World

ਸੈਟ ਤੋਂ ਬਾਅਦ:

Hello World

ਉਦਾਹਰਣ 2

ਐਲੀਮੈਂਟ <a> ਦੇ href ਪ੍ਰਤੀਯੋਗਿਤਾ ਨੂੰ ਸੈਟ ਕਰੋ:

const attr = document.createAttribute("href");
attr.value = "";
const anchor = document.getElementById("myAnchor");
anchor.setAttributeNode(attr);

ਸਵੈ ਦੀ ਜਾਂਚ ਕਰੋ

ਸੈਟ ਤੋਂ ਪਹਿਲਾਂ:

codew3c.com ਨੂੰ ਦੇਖੋ

ਸੈਟ ਤੋਂ ਬਾਅਦ:

codew3c.com ਨੂੰ ਦੇਖੋ

ਵਿਧੀ

element.setAttributeNode(newAttr)

ਪੈਰਾਮੀਟਰ

ਪੈਰਾਮੀਟਰ ਵਰਣਨ
newAttr ਲਾਜ਼ਮੀ। ਜੋ ਪ੍ਰਤੀਯੋਗਿਤਾ ਨੂੰ ਜੋੜਨਾ ਹੈ, ਜਾਂ ਜਿਸ ਦਾ ਅਕਾਰ ਸੋਧਣਾ ਹੈ ਉਸ ਦੇ ਅਕਾਰ ਨੂੰ ਦਰਸਾਉਣ ਵਾਲਾ Attr ਨੂੰ ਦਰਸਾਉਣਾ ਹੈ。

ਰਿਟਰਨ ਵੈਲਿਊ

ਪ੍ਰਕਾਰ ਵਰਣਨ
ਆਬਜੈਕਟ

ਬਦਲੇ ਹੋਏ ਪ੍ਰਤੀਯੋਗਿਤਾ ਨੂੰ ਦਰਸਾਉਣ ਵਾਲਾ Attr ਆਬਜੈਕਟ

ਜੇਕਰ ਕੋਈ ਪ੍ਰਤੀਯੋਗਿਤਾ ਨਹੀਂ ਬਦਲੀ ਤਾਂ null ਹੈ。

ਫੈਲਾਉਣਾ

ਇਹ ਮੰਥਨ ਵਿੱਚ ਨਿਮਨਲਿਖਤ ਵਾਲੇ DOMException ਅਸ਼ਾਂਤਾ ਦਿੰਦਾ ਹੈ:

ਅਸ਼ਾਂਤਾ ਵਰਣਨ
INUSE_ATTRIBUTE_ERR newAttr ਇਹ ਪਹਿਲਾਂ ਤੋਂ ਹੀ ਕਿਸੇ ਹੋਰ Element ਨੂੰ ਅਕਾਰ ਦੀ ਸੋਧ ਦੀ ਮੈਂਬਰ ਹੈ。
NO_MODIFICATION_ALLOWED_ERR ਮੌਜੂਦਾ Element ਨੂੰ ਰੀਡ-ਓਨਲੀ ਹੈ, ਇਸ ਦੇ ਅਕਾਰ ਦੀ ਸੋਧ ਨਹੀਂ ਕੀਤੀ ਜਾ ਸਕਦੀ ਹੈ。
WRONG_DOCUMENT_ERR newAttr ਦਾ ownerDocument ਪ੍ਰਤੀਯੋਗਿਤਾ ਵਿੱਚ ਜਿਸ ਨੂੰ ਸੈਟ ਕਰਨਾ ਹੈ ਦੇ ਐਲੀਮੈਂਟ ਨੂੰ ਅਲੱਗ ਹੈ。

ਬਰਾਊਜ਼ਰ ਸਮਰਥਨ

element.setAttributeNode() ਇਹ DOM Level 1 (1998) ਵਿਸ਼ੇਸ਼ਤਾ ਹੈ。

ਸਾਰੇ ਬਰਾਊਜ਼ਰਾਂ ਇਸ ਨੂੰ ਪੂਰੀ ਤਰ੍ਹਾਂ ਸਮਰਥਨ ਕਰਦੇ ਹਨ:

ਚਰਮੋਸ ਆਈਈ ਐਜ਼ਡ ਫਾਇਰਫਾਕਸ ਸੈਫਾਰੀ ਓਪਰਾ
ਚਰਮੋਸ ਆਈਈ ਐਜ਼ਡ ਫਾਇਰਫਾਕਸ ਸੈਫਾਰੀ ਓਪਰਾ
ਸਮਰਥਨ 9-11 ਸਮਰਥਨ ਸਮਰਥਨ ਸਮਰਥਨ ਸਮਰਥਨ