开发者

jQuery: Removing HTML-element while keeping it's children

I want to add HTML like this:

<div><img src="item.png"/>&nbsp;<a href="#"><span>Hello</span></a></div>

but in some cases I need to get rid of the wrapping a-element, so it looks like this:

<div><img src="item.png"/>&nbsp;<span>Hello</span></div>

This a-element could be anywhere in arbitrary HTML-fragments. I grab it by a[href="#"]. This HTML is not part of the DOM, it get's added to the DOM after the a-element was removed.

I went to all kind of stuff jQuery offers for this, but didn't make it. My main problem is, that there seems to be no way to apply a selector to HTML created by jQuery like this:

$("html code from above");

I tried to get the a-element replacing it with it's inner HTML, but all my constructs with find() and replaceWith() fail, mostly just the <span>Hello</spa开发者_如何学JAVAn> is left :(

How does a jQuery-pro solve this?


Wouldn't the unwrap feature do what you want?

If you just want to remove the surrounding tag (like an anchor)


What you need to do is set the context of your selector. See this reference: http://api.jquery.com/jquery/#selector-context

In your case, when you do the selection to replace the link, set the context as the HTML fragment that you are modifying. Here's an example:

$(function() {
    //create snippet
    var mySnippet = $('<div><img src="item.png"/>&nbsp;<a href="#"><span>Hello</span></a></div>');

    //remove the link, using the snippet as the context
    $('a[href="#"]', mySnippet).replaceWith($('a[href="#"]', mySnippet).html());

    //insert the modified snippet
    $('body').append(mySnippet);
});

And here's a demo of that in action (not very exciting, but shows that it works): http://jsfiddle.net/Ender/dQ32B/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜