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

882 Views Asked by At

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.

3

There are 3 best solutions below

0
Marik Ishtar On BEST ANSWER

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>"));
  });

});
0
Askme23 On

You need to use syntax with callback.

inText.replaceWith(function() {
    return "<div class='in-text'></div>"
});
0
MichaelvE On

You need to actually create the element that you want to add. Currently you're just adding text that happens to be coded like an element, but it is interpreting it as text only. So, first create the new element, then add your class to the element, then use replaceWith to swap the element with your new one:

$(document).ready(function() {
  var inText = $("input[type='text']");

  inText.each(function(index) {
    var item = inText[index];
    var newDiv = document.createElement("DIV");
    newDiv.classList.add("in-text");
    newDiv.innerHTML = "New DIV added";
    item.replaceWith(newDiv);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' placeholder='Test...' name='txtTest' id='txtTest'>