So, I have an HTML string that looks just like this:
<div>
<div class="venue-tooltip">
Filling station
<div>
<a class="manage-venue-details" rel="venue-id-10" href="javascript:void(0);">Add filling station info</a>
</div>
</div>
</div>
I want to get all the contents without the "a" element, so basically to have something like this:
<div>
<div class="venue-tooltip">
Filling station
<div>
</div>
</div>
</div>
The HTML is loaded in a js string and I have tried those variants:
$(':not(a)', myHtmlStr开发者_JS百科ing);
$(myHtmlString).not('a');
Both of them return unfiltered HTML. Any ideas?
My jQuery version is 1.6.1 and I test the above with Firefox 6
You cannot use DOM manipulation functions to change a string. Try using regular expresions:
code.replace(/<a( |>).*?<\/a>/gi,"");
It's more efficient than convert string in DOM, manipulate and then convert it again in again in a string.
Both not
filters will search only on the first level, and not down the tree, they filter collections and do not process the DOM tree recursively.
Assuming that myHtmlString IS a jQuery object (so it's valid context)
$(':not(a)', myHtmlString);
will return collection of the 2 DOM nodes, contained in the myHhtmlString
, as neither of them is an 'a' element
$(myHtmlString).not('a');
will also return a collection, but with the original HTML, as it's the only element provided and it's not an 'a' element. The difference between the 2 versions is the context provided in the first line of code, so it filter's the children elements of myHtmlString. If you change div.venue-tooltip
to a.venue-tooltip
, you will see it filtered in the first version.
This would work, although it's long winded and I have doubts about it's efficiency-
var h = '<div><div class="venue-tooltip">Filling station<div><a class="manage-venue-details" rel="venue-id-10" href="javascript:void(0);">Add filling station info</a></div></div></div>';
$(h).find("a").each(function () {
//need to get full outer html for replace to work
h = h.replace($(this).clone().wrap('<div></div>').parent().html(),'')
})
alert(h);
Demo - http://jsfiddle.net/XBjNS/
(function($) {
$.strRemove = function(theTarget, theString) {
return $("<div/>").append(
$(theTarget, theString).remove().end()
).html();
};
})(jQuery);
var htmlToBeChanged=$("#123").html();
var changedHtml= $.strRemove("a",htmlToBeChanged)
console.log(changedHtml);
Live Demo
Try this
$(myHtmlString).find('a').remove();
$(myHtmlString).appendTo('body');
精彩评论