0

I have this <p> tag

<p class='form-control' data-color='inherit' data-width='12' data-type='sh_info' name='shortcode[]' data-style=''>Some dynamic text</p>

and I want, on click to replace it with a textarea tag, but I want all my data and classes to persist. I fount this function in jquery

$( "p.form-control" ).click(function() {
  $( this ).replaceWith( "<textarea>" + $( this ).text() + "</textarea>" );
});

but I was wondering is there a function that allows you to substitute just the tag with something else?

Cr1xus
  • 427
  • 3
  • 20

1 Answers1

0

You can use this:

function ReplaceElement(elementToReplace, currentType, newType) {
  // Convert the elementToReplace into its string representation
  var tmp = document.createElement("div"); // Create div to wrap the elementToReplace in
  tmp.appendChild($(elementToReplace).clone()[0]); // Clone the elementToReplace and add it to the container tmp element

  // Replace the current tags with the new tags and insert after the elementToReplace
  $(tmp.innerHTML.replace("<" + currentType, "<" + newType).replace("/" + currentType + ">", "/" + newType + ">")).insertAfter(elementToReplace);


  $(elementToReplace).remove(); // Remove the old element from the DOM
}

like this:

$( "p" ).click(function() {
  ReplaceElement(this, "p", "textarea");
});
SupposedlySam
  • 675
  • 5
  • 14