0

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?

David Min
  • 1,246
  • 8
  • 27
  • Why would `someObject[objectKey] = null;` not work for you? – iLuvLogix Jul 14 '22 at 13:32
  • 1
    Why does the syntax used to express the value of an attribute in a serialisation of a DOM matter? – Quentin Jul 14 '22 at 13:32
  • I would recommend using `removeAttribute` because some attributes may or may not accept values and still work example `checked` on radio button and checkboxes. https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute – Manish Jul 14 '22 at 13:34
  • 1
    Does this answer your question? [Set attribute without value](https://stackoverflow.com/questions/13159180/set-attribute-without-value) – Justinas Jul 14 '22 at 13:39
  • @Quentin It doesn't matter to the DOM. This is out of human readability considerations for debugging ergonomics purposes. – David Min Jul 14 '22 at 15:07
  • @Justinas That helped indeed, although that was a jQuery answer. I posted the not jQuery answer. – David Min Jul 14 '22 at 15:08

2 Answers2

2

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>
David Min
  • 1,246
  • 8
  • 27
  • 1
    "*This will not lead the element to have a `=""` in its tag*" - but (and this may, or may not, be a problem for OP) it *does* result in `=""` in the DOM in Firefox (this isn't a criticism of the answer, but information for someone wanting the same outcome in future). – David Thomas Jul 14 '22 at 15:12
  • 1
    @DavidThomas Thanks for that! Updated to include disclaimer – David Min Jul 14 '22 at 15:15
-2

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

Abhay
  • 3
  • 3
  • 2
    The OP is asking how to have a boolean attribute which is present without the `="..."` part. They aren't asking how to remove the attribute. – Quentin Jul 14 '22 at 13:52