niutech niutech - 4 months ago 8
jQuery Question

Insert HTML element or replace its contents if it exists

I have a following HTML:

<ul>
<li>One</li>
<!-- here may or may not be: <li></li> -->
</ul>


What is the most concise/snippy way to write the following using jQuery:

var $firstLi = $('li:first-child');
if (!$firstLi.next().length) {
$firstLi.after('<li>Two</li>');
} else {
$firstLi.next().html('Two');
}


?



var $firstLi = $('li:first-child');
if (!$firstLi.next().length) {
$firstLi.after('<li>Two</li>');
} else {
$firstLi.next().html('Two');
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>One</li>
<li></li>
</ul>




Answer

I found a simple one-liner:

$('li:first-child').next().remove().end().after('<li>Two</li>');