I've got a page with several li elements. I'm trying to replace one of those li elements with an array of elements using jQuery. When I pass either a jQuery object or array of jQuery objects to replaceWith(), however, the element is replaced with the string "[object Object]" for each item in the array.
let newElement = $("<li class='myClass'></li>");
$("#myListItem").replaceWith(newElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<ul>
<li id="myListItem"></li>
</ul>
</div>
I expect to see:
<div class="container">
<ul>
<li class='myClass'></li>
</ul>
</div>
Instead, I get:
<div class="container">
<ul>
[object Object]
</ul>
</div>
EDIT:
@Barmar and @Bergi were correct in the comments below. Something is causing .replaceWith() invoked on jQuery objects to trigger the native .replaceWith() method. The output in the snippet below demonstrates exactly what I'm seeing when I run my code (except my code is ostensibly using the jQuery method).
let newElement = $("<li class='myClass'>New li</li>");
let newElement1 = $("<li class='myClass'>New li</li>");
let newElement2 = $("<li class='myClass'>New li</li>");
let elementArray = [newElement, newElement1, newElement2]
document.getElementById('myListItem').replaceWith(elementArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<ul>
<li id="myListItem"></li>
</ul>
</div>