niutech
niutech

Reputation: 29942

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>

Upvotes: 0

Views: 75

Answers (2)

niutech
niutech

Reputation: 29942

I found a simple one-liner:

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

Upvotes: 0

Tushar
Tushar

Reputation: 87203

If you want concise way

var $firstLi = $('ul li:eq(1)'); // Index is zero based
$firstLi.length ? $firstLi.text('Two') : $('ul').append('<li>Two</li>');

If you want readable code, then you already have the code.

Upvotes: 2

Related Questions