Borislav Hadzhiev
Sun Jan 09 2022·2 min read
Photo by Micah Hallahan
Use the setAttribute()
method to change the name
attribute of an element,
e.g. box.setAttribute('name', 'example-name')
. The method sets or updates the
value of an attribute on the specified element.
Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box" name="my-box" style=" background-color: salmon; color: white; width: 150px; height: 150px; margin: 10px; " > Box content </div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const box = document.getElementById('box'); box.setAttribute('name', 'example-name');
We used the
setAttribute
method to change the value of the element's name
attribute.
The method takes the following 2 parameters:
name
- the name of the attribute to be set.value
- the value to assign to the attribute.If you need to remove an attribute from the element, you can use the
removeAttribute
method.
const box = document.getElementById('box'); box.removeAttribute('name');
The removeAttribute
method removes the attribute with the specified name from
the element.
If you need to get the value of the name
attribute on the element, you can use
the getAttribute()
method.
const box = document.getElementById('box'); box.setAttribute('name', 'example-name'); // 👇️ "example-name" console.log(box.getAttribute('name'));
The getAttribute
method returns the value of the specified attribute on the
element.
null
or ""
(empty string), depending on the browser's implementation.If I load the page with the example above, I can see that the value of the
name
attribute has been changed successfully.