开发者

How to append html to first occurance of string after selected element

开发者 https://www.devze.com 2022-12-24 15:10 出处:网络
I have html like so: <div class=foo> (<a href=forum.example.com>forum</a>) <p> Some html here....

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>开发者_StackOverflow社区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?


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()


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>');


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消