Is it possible to use jQuery.not()
chained with jQuery.html()
?
winner.not('a').html()
Where winner
is a jQuery object/wrapped set, I am trying to return HTML with anchors removed.
Is it possible to use jQuery.not()
chained with jQuery.html()
?
winner.not('a').html()
Where winner
is a jQuery object/wrapped set, I am trying to return HTML with anchors removed.
It is possible but that won't give you the result you expect. not('a')
will filter a
tags from your winner
collection but html()
will return you the value of the first item in the collection.
so if your winner
has [div#i1 div#i2 a div#i3 a]
, not('a')
will reduce this set to [div#i1 div#i2 div#i3]
and html()
will return HTML contents of div#i1
.
If you want to remove anchors from HTML I think you should first get is using .html()
method and then do a replace on the value returned with some regular expression that will strip the anchors.
Alternatively, you could use something like this:
var noanchors = '';
winner.not('a').each(function() { noanchors = noanchors + $(this).html(); )
to get the concatenation of the non-a elements' html. However, this may miss any top-level text in between the various tag-enclosed items.
.html()
is going to return the innerHTML - which will include any A tags inside, you may be able to do something like this though:
// clone the matched div:
var copy = winner.clone();
// remove all A tags from the DOM
copy.find("a").remove();
// get the html.
var noanchors = copy.html();
Also - If you wanted to get the text within the A still - but not the A itself - you could use:
// for each A tag
copy.find("a").each(function() {
//insert the text within ourselves to the document directly before us.
$(this).before($(this).text());
// then delete ourselves
$(this).remove();
});
Although that might actually get a little messy if the <a>
has any other tags within it - it should illustrate the idea.