tags:

views:

47

answers:

3
<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>

A: 
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'));
Danny Chen
insertAfter is not the same as append! Your first snippet will create will create this `<strong>title{$el}</strong>` if there are no cites and you second snippet will create `<strong>title</strong>{$el}`, and`<cite>...{$el}</cite>` versus `<cite>...</cite>{$el}`
jigfox
`nextAll` selects all `cite` tags after the `strong`, not just the immediately following ones.
Tgr
@Tgr - "after strong" is exactly what he want, isn't it?
Danny Chen
@Danny Chen: not fully clear from the question, but I don't think so. Consider `<strong /><cite /><a>ank</a><cite />`
Tgr
A: 

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))
jigfox
`$('strong, strong ~ cite').filter(':last').after($el)`? Probably less efficient, but more readable.
Tgr
What does `~` mean in `strong ~ cite:last` ?
wamp
@wamp: see my [Edit]
jigfox
On second thought, this has the same potential problem as the `nextAll()` solution.
Tgr
@Tgr: You're right about the potential problem, but it depends on how to interpret the question. I think wamp needs to clearify question, before we can make the right answer
jigfox
@Tgr, yes you are right, but the dom structure in my case is easy enough so that case won't happen,so I accepted it:)
wamp
A: 
var anchor = $('strong');
while (anchor.next('cite').length) {
  anchor = anchor.next();
}
anchor.after($el);
Tgr