How To Remove The ID Attribute From An Element Using JavaScript?

Remove the ID attribute from an Element using JavaScript

You will know how to remove the ID attribute from an element using JavaScript using some methods like using removeAttribute() or removeAttr(). This is one of the most important skills when you work with elements’ attributes in Javascript.

Remove the ID attribute from an element using JavaScript

Using removeAttribute()

This function changes to the attribute declared in its parameter of the HTML element by removing the attribute with the given name from the element. The syntax and parameter of this function is:

Syntax:

removeAttribute(attribute)

Parameter:

  • attribute: The name of the attribute you want to remove.

You can use the removeAttribute() function to call it on an element to remove the ID attribute by passing the string “id” to its argument.

let body = document.body;

// Remove the id attribute from ‘body’
body.removeAttribute('id')

The example above shows that we have removed the id attribute from the body of the HTML document. This function will delete the declaration id = ‘…’ in its property. However, if it cannot find that attribute (maybe because that is not declared yet), this function will not raise an error. So in short, this method won’t return anything in any case, it just changes and removes the attribute of an element if there is any.

Using jQuery removeAttr()

jQuery is a fast, small, and feature-rich JavaScript library. However, it is not a built-in library in JavaScript. You have to import the source code of this library to use this method. All you have to do is to declare this script tag in the head tag:

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script> 

Here is the syntax and usage of removeAttr() method in jQuery.

Syntax:

$(element).removeAttr(attribute);

Parameters:

  • element: The element name, must begin with a letter ([A-Za-z]) and can be followed by some letters or digits ([0-9]), colons (“:”), underscores (“_”), hyphens (“-“), and periods (“.”).
  • attribute: the attribute name you want to remove.
let body = document.body;

// Remove the id attribute from ‘body’
$('body').removeAttr('id');

In fact, the .removeAttr() method in jQuery uses the method removeAttribute() in JavaScript so it won’t return anything, but it can help you to reduce the code when finding the element to remove (such as body) and it can be called directly by a jQuery object. Moreover, it also accounts for different attributes naming among browsers.

Summary

We have learned to remove the ID attribute from an element using JavaScript in two ways. With the help of our instructions in this tutorial and others, you can quickly achieve the task. In conclution, you should use the first solution: using removeAttribute() because it is the fastest way.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *