Remove Attribute from Element

by||1 min read
Remove Attribute from Element
Remove Attribute from Element

Removing an attribute from a DOM Element is pretty easy and straight forward. We can use the removeAttribute funtction in JavaScript. As we can see on caniuse this method is widely supported by browsers and can be used in your JavaScript code in the following way:

<div id="myTargetElement" class="yellow">
  I would like to remove the class from this DIV element
</div>
const element = document.getElementById('myTargetElement');
element.removeAttribute('class');

This code will remove the class attribute from your element. To be sure not to call the removeAttribute on a non existing element we can wrap the function call into an if:

const element = document.getElementById('myTargetElement');
if (element) {
  element.removeAttribute('class');
}

If you would like to dive deeper in the topic or learn about it's siblings "hasAttribute" and "setAttribute" you can visit the official Mozilla MDN docs.

Thank you for reading this far! Let’s connect. You can @ me on Twitter (@debilofant) with comments, or feel free to follow. Please like/share this article so that it reaches others as well.

© Copyright 2022 - Ersocon - All rights reservedVer. 2.3.5.2