Reputation: 3537
I'm trying to do the following;
(1) Clone the element.
(2) Create a new element and concat with the cloned element.
(3) Replace the cloned element with the new one.
var clonedElement = $('.container input#input_text').clone();
$(".container input#input_text").replaceWith('<div class="custom-container"><p class="custom-text">Some Text</p>' + clonedElement + '</div>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<!-- Some auto generated element -->
<!-- Some auto generated element -->
<form>
<!-- Some auto generated element -->
<input id="input_text" />
<!-- Some auto generated element -->
</form>
<!-- Some auto generated element -->
<!-- Some auto generated element -->
</div>
The cloned doesn't convert back to its original element, it's just object.
Upvotes: 0
Views: 74
Reputation: 147146
You can append
the cloned element to your new div
and then replace the contents of the element with that:
var clonedElement = $('.container input#input_text').clone();
$(".container input#input_text")
.replaceWith($('<div class="custom-container"><p class="custom-text">Some Text</p></div>')
.append(clonedElement));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<!-- Some auto generated element -->
<!-- Some auto generated element -->
<form>
<!-- Some auto generated element -->
<input id="input_text" />
<!-- Some auto generated element -->
</form>
<!-- Some auto generated element -->
<!-- Some auto generated element -->
</div>
Upvotes: 1
Reputation: 1074008
That's because when you use string concatenation on an element, you get the string "[object HTMLElement]"
for it.
You could use wrap
with the div
markup, then before
to add the paragraph:
var clonedElement = $('.container input#input_text').clone();
$(".container input#input_text")
.wrap("<div class=custom-container></div>")
.before('<p class="custom-text">Some Text</p>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<!-- Some auto generated element -->
<!-- Some auto generated element -->
<form>
<!-- Some auto generated element -->
<input id="input_text" />
<!-- Some auto generated element -->
</form>
<!-- Some auto generated element -->
<!-- Some auto generated element -->
</div>
Upvotes: 0