Search code examples
javascriptjqueryhtmlcontenteditableclassname

How to change class of focused contenteditable element on button click using jquery?


I am trying to change class of an element located in contenteditable div

My current code is :

<button>swap class</button>
<div contenteditable="true">
    <h1 class="line-height-1">Your Headline Here</h1>
</div>    
<div contenteditable="true">
    <h1 class="line-height-1">Your Headline Here</h1>
</div>

I want to replace the class .line-height-1 to another for currently selected editable div when clicking on button.

Can anyone Help ??


Solution

  • When you click on button, focused element does blured. You need to store focused element in variable and change it on button click. After button click make it focused.

    var element;
    $("div[contenteditable]").focus(function(){
        element = this;
    });
    $("button").click(function(){
        $(element).focus().find("h1").removeClass("line-height-1").addClass("newClass");
    });
    .line-height-1 { color: red }
    .newClass { color: blue }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button>swap class</button>
    <div contenteditable="true">
      <h1 class="line-height-1">Your Headline Here</h1>
    </div>
    <div contenteditable="true">
      <h1 class="line-height-1">Your Headline Here</h1>
    </div>