JavaScript’s Document.createAttribute()
method creates and returns a new attribute node that implements the Attr
interface.
Syntax
Document.createAttribute(parameter);
Parameters
A string containing the name of the attribute.
Return value
An Attr
node.
Exceptions
InvalidCharacterError
DOMException
Thrown if the parameter is not a valid XML name. XML names may contain alphanumeric characters, hyphens, periods, and underscores but cannot start with a number, hyphen, or period.
Examples
Here is an example of using the JavaScript createElement()
method.
Consider the following line of HTML:
<p>Visiting the JavaScript Guide at least once a day is a habit of mine.</p>
How can we add a class
attribute to the p
element?
Well, we can select the element with the querySelector()
method, create a new attribute node, and attach the node to the element:
let p = document.querySelector('p');
let attribute = document.createAttribute('class');
attribute.value = 'yellow';
p.setAttributeNode(attribute);
Now our line of HTML looks like this:
<p class="yellow">Visiting the JavaScript Guide at least once a day is a habit of mine.</p>
Browser compatibility
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
Chrome (Android)
|
Firefox (Android)
|
Opera (Android)
|
Safari (iOS)
|
Samsung Internet
|
WebView (Android)
|
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
createAttribute() |
1 | 12 | 1 | 6 | 12.1 | 1 | 18 | 4 | 12.1 | 1 | 1.0 | 4.4 |