Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
65
rated 0 times [  70] [ 5]  / answers: 1 / hits: 40245  / 13 Years ago, wed, february 8, 2012, 12:00:00

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



<p> to <p contenteditable>



<p> to <p data-example>


More From » html

 Answers
132

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

[#87583] Tuesday, February 7, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nestorjarettg

Total Points: 451
Total Questions: 108
Total Answers: 108

Location: Rwanda
Member since Thu, Feb 10, 2022
2 Years ago
;