Search code examples
javascripthtmldom-manipulation

How to add boolean attribute using JavaScript


How do you add boolean attributes using JavaScript? For example, how can you change:

<p> to <p contenteditable>

<p> to <p data-example>


Solution

  • In general, you can use element.setAttribute('attributeName', 'value') or element.propertyName = value to toggle an element’s attributes or properties.

    Boolean attributes

    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';