i am trying to use javascript to remove an attribute from a DOM node:
<div id="foo">Hi there</div>
First i add an attribute:
document.getElementById("foo").attributes['contoso'] = "Hello, world!";
Then i remove it:
document.getElementById("foo").removeAttribute("contoso");
Except the attribute is still there.
So then i try to really remove it:
document.getElementById("foo").attributes['contoso'] = null;
And now it's null
, which is different than when it started, which was undefined
.
What is the correct way to remove an attribute from an element?
jsFiddle playground
Note: Replace the attribute contoso
, with the attribute required
, and you'll understand what i'm trying to do.
foo.attributes.contoso foo.hasAttribute("contoso")
====================== ===========================
Before setting undefined false
After setting Hello, world! false
After removing Hello, world! false
After really removing null false
The removeChild() method of the Node interface removes a child node from the DOM and returns the removed node.
Definition and Usage. The remove() method is used to remove an option from a drop-down list. Tip: To add an option to a drop-down list, use the add() method.
removeAttr() method. With jQuery, you can use the . removeAttr() method to remove the class attribute from an element. It is equivalent to the JavaScript's removeAttribute() method.
The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.
Don't use the attributes
collection to work with attributes. Instead use setAttribute and getAttribute:
var foo = document.getElementById("foo");
foo.hasAttribute('contoso'); // false
foo.getAttribute('contoso'); // null
foo.setAttribute('contoso', 'Hello, world!');
foo.hasAttribute('contoso'); // true
foo.getAttribute('contoso'); // 'Hello, world!'
foo.removeAttribute('contoso');
foo.hasAttribute('contoso'); // false
foo.getAttribute('contoso'); // null,
// It has been removed properly, trying to set it to undefined will end up
// setting it to the string "undefined"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With