How do you add boolean attributes using JavaScript? For example, how can you change:
<p>
to <p contenteditable>
<p>
to <p data-example>
Javascript's dynamic type system in action. I'd assume the + operand will auto-typecast the values that are being 'merged', resulting in true being treated as a numeric? Because you can't add booleans, so it converts them to numbers first.
The variable will become what ever type you assign it. Initially it is undefined . If you assign it 'true' it will become a string, if you assign it true it will become a boolean, if you assign it 1 it will become a number. Subsequent assignments may change the type of the variable later.
To declare a Boolean in JavaScript, you need to assign true or false value.
In JavaScript, booleans are the primitive data types that can either be true or false . For example, const a = true; const b = false; Note: If you wrap true or false in a quote, then they are considered as a string.
node.setAttribute(attributeName, ''); // example: document.body.setAttribute('hidden', '');
Note the empty string as the second argument!
Use node.removeAttribute(attributeName)
to remove an attribute as mentioned by others.
In general, you can use element.setAttribute('attributeName', 'value')
or element.propertyName = value
to toggle an element’s attributes or properties.
For boolean attributes, set the attribute with the same-named value:
element.setAttribute('disabled', 'disabled');
Removing a boolean attribute works the same way as other attributes:
element.removeAttribute('disabled');
However, neither of your two examples are boolean attributes!
contenteditable
contenteditable
is not a boolean attribute, it’s an enumerated attribute. Its possible values are the empty string, "true"
, and "false"
.
While setAttribute
seems overkill in this case, you could use it:
element.setAttribute('contenteditable', 'true'); // to undo: element.removeAttribute('contenteditable');
The property name for the contenteditable
attribute is contentEditable
(note the capital E
), and it recognizes the values 'true'
, 'false'
, and 'inherit'
— so you could just use:
element.contentEditable = 'true'; // to undo: element.contentEditable = 'false';
Note that 'true'
and 'false'
are strings here, not booleans.
data-example
For the data-example
attribute, you could use:
element.setAttribute('data-example', 'some value'); // the value should be a string // to undo: element.removeAttribute('data-example');
Or, in browsers who support dataset
(see the ones highlighted in light green on http://caniuse.com/dataset), you could use:
element.dataset.example = 'some value';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With