Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an attribute from a DOM element using Javascript?

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.

State table

                       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
like image 933
Ian Boyd Avatar asked Sep 12 '13 17:09

Ian Boyd


People also ask

Which JavaScript method removes a node from the DOM?

The removeChild() method of the Node interface removes a child node from the DOM and returns the removed node.

Is there a remove function in JavaScript?

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.

How do I delete a class attribute?

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.

How do I grab an element from a DOM?

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.


1 Answers

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"
like image 79
Paul Avatar answered Oct 16 '22 13:10

Paul