How to replace div with textarea & vice versa using jquery

Lets say I have bellow Div

<div class="containerDiv"> <span> this is my content </span> </div>

now I want to replace the span with text area & also want Want the same text “this is my content” in textarea

So how can we replace div or span with textarea using jquery?

Well Bellow is simple jquery for this

 var bodyText = $("#containerDiv span").text();    // get text of span
 var textArea = $("<textarea style='width:100% ; height:200px' />");   // create new text area
 textArea.val(bodyText);  // add value to text area
 $("#containerDiv span").replaceWith(textArea); // replace span with textarea
 textArea.focus();  // focus on textarea

Bellow will be the new HTML

<div class="containerDiv"> <span> <textarea style='width:100% ; height:200px'> this is my content </textarea> </span> </div>

This way we can replace any div or span with any control i.e. textarea, textbox, checkbox, etc.

We can also do vice versa i.e. replacing textarea with span or div

Bellow is jquery for it.

var bodyText = $("#containerDiv textarea").val();
var body = $("<span> </span>");
$("#containerDiv textarea").replaceWith(body);


  • yassershaikh

    Would be great to have a jsfiddle to play around with :)