replace ul list child element

Viewed 113

say i have a list

<ul class="ul-1">
  <li class="li-1">xx -1</li>
  <li class="li-2">xx -2</li>
  <li class="li-3">xx -3</li>
</ul>

i then save it as

var list = $('.ul-1').html();

i can populate another element i.e

$('.ul-2').html(list);

but what if I wanted to replace the first list element <li class="li-1">xx -1</li> with another list element, how do I do this using the list variable? thanks

1 Answers

Firstly note that it's generally better practice to work with references to the elements in the DOM rather than serialising them to strings which need to be deserialised again when re-added to the DOM.

In addition, if you work with the li references you can use jQuery to retrieve the first() of them and then replaceWith() to change it as necessary. Try this:

var $list = $('.ul-1 > li');
$list.appendTo('.ul-2');
$list.first().replaceWith('<li>Foobar</li>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="ul-1">
  <li class="li-1">xx -1</li>
  <li class="li-2">xx -2</li>
  <li class="li-3">xx -3</li>
</ul>

<ul class="ul-2"></ul>

Related