Question

My goal here is to make multiple divs editable by the click of a button. Is there a way to do this by using a class instead of an ID? I'd like to be able to add the editable class to multiple divs throughout my site. Is there a plugin or module that would be well suited for this task? I don't want to edit the code or formatting in the browser, the text content only. Your thoughts?

test test test test1 test test test test2 test test test test3
<script>
    var editorBtn = document.getElementsByClassName('editBtn');
    var element = document.getElementsByClassName('editable');

    editorBtn.addEventListener('click', function(e) { 
        e.preventDefault();

        if (element.isContentEditable) {
        element.contentEditable = 'false';
        editBtn.innerHTML = 'update';

      } else {
        element.contentEditable = 'true';
        editBtn.innerHTML = 'done';
        }
    });
</script>
Était-ce utile?

La solution

getElementsByClassName is going to return an array. You probably want to access your button via ID, and the elements via class.

<script>
 var editorBtn = document.getElementById('editBtn');



 editorBtn.addEventListener('click', function(e) { 
    e.preventDefault();
    var elements = document.getElementsByClassName('editable');
    for(var i =0;i<elements.length;i++){
     if (elements[i].isContentEditable) {
      elements[i].contentEditable = 'false';
      editBtn.innerHTML = 'update';
     } else {
      elements[i].contentEditable = 'true';
      editBtn.innerHTML = 'done';
     }
    }
 });
</script>

you should probably pull the editBtn.innerHTML outside the loop, but, since you are making them all editable, or all not editable, it should work as desired as-is.

Add 'editable' class to to your hearts content.

Edit: The above is just an example of how to modify attributes to elements with a given class name (editable). Whether the attributes you are modifying will achieve your desired goal of making the element allow/prohibit editing, is not guaranteed.

Autres conseils

If you want to add a class to a set of divs or elements, use Jquery

$(".classToSelect").addClass("classToInsert")

If this is not what you want, plz clarify your question

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top