Как удалить атрибут из элемента DOM с помощью Javascript?
Я пытаюсь использовать javascript для удаления атрибута из DOM node:
<div id="foo">Hi there</div>
Сначала я добавляю атрибут:
document.getElementById("foo").attributes['contoso'] = "Hello, world!";
Затем я удаляю его:
document.getElementById("foo").removeAttribute("contoso");
За исключением того, что атрибут все еще существует.
Итак, я пытаюсь удалить его:
document.getElementById("foo").attributes['contoso'] = null;
И теперь он null
, который отличается от того, когда он начинался, который был undefined
.
Каков правильный способ удаления атрибута из элемента?
игровая площадка jsFiddle
Примечание: замените атрибут contoso
атрибутом required
, и вы поймете, что я пытаюсь сделать.
Таблица состояний
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
Ответы
Ответ 1
Не используйте коллекцию attributes
для работы с атрибутами. Вместо этого используйте setAttribute и 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"