views:

39

answers:

3

Hello,

I have html like so:

<div class=foo>
  (<a href=forum.example.com>forum</a>)
  <p>
  Some html here....
</div>

And I want to insert another link after the first one, like so:

<div class=foo>
  (<a href=forum.example.com>forum</a>) <a href=blog.example.com>blog</a>
  <p>
  Some html here....
</div>

...but because it is enclosed in () I cannot use:

$('div.foo a:first').append(' <a href=blog.example.com>blog</a>');

...which would place it before the ).

So how can I extend my jQuery selection to select the literal ) or do I need to use another solution?

+1  A: 

Could you possibly select the next <p> tag and prepend (actually...use the before method) the link?

$('div.foo a:first').next('<p>').before(' <a href=blog.example.com>blog</a>');
Topher Fangio
+2  A: 

You can either match and replace the whole (<a />) string, or place another element (such as a span) around the whole thing.

<span>(<a href=forum.example.com>forum</a>)</span>

Append is also inserting the new anchor tag inside the existing anchor. You'll probably find you're looking for after()

Matt
Correct regarding `after()`
A: 

One should never modify XML/HTML (especially untrusted/illformatted) by regular expressions, but if you are really desperate:

var container = $('div.foo');
var append = '<a href="...">...</a>';
var html = container.html();
var replaced = html.replace(/\(<a [^\)]+\)/, "$& " + append);
container.html(replaced);

Note that the above will fail if you have ")" character inside a-tag.

jholster