How do you add boolean attributes using JavaScript? For example, how can you change:
<p> to <p contenteditable>
<p> to <p data-example>
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In general, you can use
element.setAttribute('attributeName', 'value')orelement.propertyName = valueto toggle an element’s attributes or properties.Boolean attributes
For boolean attributes, set the attribute with the same-named value:
Removing a boolean attribute works the same way as other attributes:
However, neither of your two examples are boolean attributes!
contenteditablecontenteditableis not a boolean attribute, it’s an enumerated attribute. Its possible values are the empty string,"true", and"false".While
setAttributeseems overkill in this case, you could use it:The property name for the
contenteditableattribute iscontentEditable(note the capitalE), and it recognizes the values'true','false', and'inherit'— so you could just use:Note that
'true'and'false'are strings here, not booleans.data-exampleFor the
data-exampleattribute, you could use:Or, in browsers who support
dataset(see the ones highlighted in light green on http://caniuse.com/dataset), you could use: