javascripthtmljqueryreplacewith

jQuery replaceWith fills in raw HTML instead of replacing with new tag: How do I fix this?


I am attempting to use the jQuery replaceWith() to replace a text input with a div element. The idea is to have this happen in the same DOM location as the respective text input. The page is as follows:

HTML (only the applicable portion):

<input type='text' placeholder='Test...' name='txtTest' id='txtTest'>

JavaScript:

$(document).ready(function() {
  var inText = $("input[type='text']");
  
  inText.each( function(index) {
    var item = inText[index];
    item.replaceWith(("<div class='in-text'></div>"));
  });
});

Output:
enter image description here

When stepping through in the Developer Tools, it starts correctly with the text input, then clears the text input and replaces with the raw HTML text rather than with a new node.

I feel like I am missing or misunderstanding something, but I cannot find what exactly that is.


Solution

  • you are using the javascript version of .replaceWith(), you need to add $() to the item

    $(item).replaceWith(("<div class='in-text'></div>"));
    

    try this:

    $(document).ready(function () {
      var inText = $("input[type='text']");
    
      inText.each(function (index) {
         var item = inText[index];
         $(item).replaceWith(("<div class='in-text'></div>"));
      });
    
    });