document.createAttribute()

Document.createAttribute() 方法创建并返回一个新的属性节点。这个对象创建一个实现了 Attr 接口的节点。这个方式下DOM不限制节点能够添加的属性种类。

语法

attribute = document.createAttribute(name)

参数

  • name ,属性的属性名。

返回值

一个 Attr 节点。

异常

  • INVALID_CHARACTER_ERR 如果参数含有非法的XML属性字符。

例子

var node = document.getElementById("div1");
var a = document.createAttribute("my_attrib");
a.value = "newVal";
node.setAttributeNode(a);
console.log(node.getAttribute("my_attrib")); // "newVal"

备注

该方法的返回值是一个类型为 Attr 的节点。你可以通过为该节点的 nodeValue 属性赋值来设置该属性节点的属性值,也可以使用常用的 setAttribute() 方法来替代该方法.

规范

Specification Status Comment
DOM
Document.createAttribute()
Living Standard 大写字符的精确表现。
Document Object Model (DOM) Level 3 Core Specification
Document.createAttribute()
Obsolete 无变更。
Document Object Model (DOM) Level 2 Core Specification
Document.createAttribute()
Obsolete 无变更。
Document Object Model (DOM) Level 1 Specification
Document.createAttribute()
Obsolete 初始定义。

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
createAttributeChrome Full support 1Edge Full support 12Firefox Full support 44
Full support 44
No support 4 — 44
Notes
Notes The parameter was not converted to its lowercase variant.
IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 44
Full support 44
No support 4 — 44
Notes
Notes The parameter was not converted to its lowercase variant.
Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android ?

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown
See implementation notes.
See implementation notes.

参见