views:

103

answers:

1

I have a blob of HTML. How can I use jQuery to remove the class attribute from all anchor tags in the blob and then return the resulting HTML?

I feel like this should work, but it doesn't:

$(blob).filter('a').removeAttr('class').end().html()

(It returns the empty string)

Bonus points if you explain why my solution is wrong.

+4  A: 

You want this:

$('<div></div>').append(blob).find('a').removeAttr('class').end().html()

.filter() takes the selected elements and removes all those that aren't <a> tags. .find() traverses into the entire tree, finding all anchor tags inside.

VoteyDisciple
This doesn't work -- suppose blob is `"something <a class='test' href='#'>alkdfjs</a>"`. Your answer outputs "alkdfjs"
Horace Loeb
Ah. I misunderstood what `blob` would be. I'll edit accordingly.
VoteyDisciple
Thanks! (To be clear, given the above definition of blob, I'm looking for this output: `something <a href='#'>alkdfjs</a>`)
Horace Loeb
Nice (weird that jQuery forces you to do this kind of hack...)
Horace Loeb