views:

35

answers:

2

Hi,

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</span> is left :(

How does a jQuery-pro solve this?

A: 

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/

Ender
Thanks Ender, this works fine. I wasn't aware of the possibility to give a context when using replaceWith.
+2  A: 

Wouldn't the unwrap feature do what you want?

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

drachenstern