Change the Name attribute of an Element using JavaScript

avatar

Borislav Hadzhiev

Sun Jan 09 20222 min read

Change the Name attribute of an Element using JavaScript #

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.

index.html
<!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.

index.js
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:

  1. name - the name of the attribute to be set.
  2. value- the value to assign to the attribute.
If the attribute already exists on the element, the value is updated, otherwise a new attribute is added with the specified name and value.

If you need to remove an attribute from the element, you can use the removeAttribute method.

index.js
const box = document.getElementById('box'); box.removeAttribute('name');

The removeAttribute method removes the attribute with the specified name from the element.

If the attribute does not exist on the element, the method returns without throwing an error.

If you need to get the value of the name attribute on the element, you can use the getAttribute() method.

index.js
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.

If the provided attribute does not exist on the element, the method returns either 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.

name attribute changed

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee