Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 555
TheDebianDuck Avatar asked Sep 01 '25 10:09

TheDebianDuck


2 Answers

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

});
like image 184
Marik Ishtar Avatar answered Sep 04 '25 05:09

Marik Ishtar


You need to use syntax with callback.

inText.replaceWith(function() {
    return "<div class='in-text'></div>"
});
like image 32
Askme23 Avatar answered Sep 04 '25 03:09

Askme23