Reputation: 783
I want to add HTML like this:
<div><img src="item.png"/> <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"/> <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?
Upvotes: 1
Views: 1393
Reputation: 16035
Wouldn't the unwrap feature do what you want?
If you just want to remove the surrounding tag (like an anchor)
Upvotes: 4
Reputation: 15221
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"/> <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/
Upvotes: 1