Search code examples
csscontenteditable

How to toggle div background color based on class name and contenteditable value


I want to change div background color based on class name 'cls-editable', which is used by javascript to find the element and then set editable attribute to be 'true' or 'false.

When editable, background is yellow. Otherwise, it's white.

HTML

<div class='cls-editable'>
  Hello
</div>


CSS:

.cls-editable, [contenteditable="true"] {
   background-color: yellow;
}

.cls-editable, [contenteditable="false"] {
   background-color: white;
}


Javascript:

if (this.checkStatus) {
  $('.dirs_row').children('.cls-editable').each(function () {
    $(this).attr('contenteditable', 'true');
  });
} else {
  $('.dirs_row').children('.cls-editable').each(function () {
    $(this).attr('contenteditable', 'false');
  });
}

But, it does not work. What's wrong with css?


Solution

  • You got it almost correct! Here is the correct solution:

    .cls-editable[contenteditable="true"] {
       background-color: yellow;
    }
    
    .cls-editable[contenteditable="false"] {
       background-color: white;
    }
    <div class='cls-editable' contentEditable="true">
      Hello
    </div>
    <div class='cls-editable' contentEditable="false">
      Hello
    </div>