Home > Enterprise >  How to set an HTML Element's attribute to null?
How to set an HTML Element's attribute to null?

Time:07-15

Using setAttribute(<key>, <value>) means the null value supplied will be converted to a string, and you end up with <element <key>="null">.

I would ideally like the element to appear as <element <key>> like <my-comp show>, instead of the above or <my-comp show=''>

How would I be able to achieve this without modifying outerHTML property please?

CodePudding user response:

Edge / Chrome only:

Set the element attribute to an empty string '' is sufficient to have the attribute value set to null (tested in Edge/Chromium). This will not lead the element to have a <attr>="" in its tag. See example below.

document.getElementById('a').setAttribute('show', '')
div {
  border: 1px solid black;
  padding: 1rem;
}
<div id='a'>Hi</div>

CodePudding user response:

You can document.getElementById("xyz").removeAttribute("show");

  • Related