<strong>title</strong>
<cite>...</cite>
<cite>...</cite>
...
<a>ank</a>
I want to append a new element $el right behind the last <cite> behind <strong>,if there is no <cite>,then append $el right after <strong>
<strong>title</strong>
<cite>...</cite>
<cite>...</cite>
...
<a>ank</a>
I want to append a new element $el right behind the last <cite> behind <strong>,if there is no <cite>,then append $el right after <strong>
var cites = $('strong').nextAll('cite');
/*Incorrect
if (cites.length==0) $('strong').append($el);
else cites.filter(':last').append($el);
*/
Notepad code. Sorry I made a mistake.
EDIT: if-else can be changed to:
$el.insertAfter(cites.length==0?$('strong'):cites.filter(':last'));
Try this:
$last_cite = $("strong ~ cite:last");
if ($last_cite.length > 0) {
$last_cite.after($el);
} else {
$("strong").after($el);
}
[EDIT]
~ Selects all sibling elements that follow after the "prev" element, have the same parent, and match the filtering "siblings" selector. source
[/EDIT]
Or in one line but not really shorter and less readable:
$el.insertAfter($last_cite.length > 0 ? $last_cite : $("strong"));
UPDATE
shorter approach:
$el.insertAfter($("strong, strong ~ cite:last").eq(-1))
var anchor = $('strong');
while (anchor.next('cite').length) {
anchor = anchor.next();
}
anchor.after($el);