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

后端 未结 1 1015
一向
一向 2020-12-31 05:30

i am trying to use javascript to remove an attribute from a DOM node:

Hi there

First i add an attribute:<

相关标签:
1条回答
  • 2020-12-31 05:33

    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"
    
    0 讨论(0)
提交回复
热议问题