Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a tag from inside a function called by .each

Tags:

jquery

Inside a function valled by .each I want to remove the a tag(s)/. Here is a non-working example:

$('div.link').has('div.entry:has(p.title:has(a[href^="http://i.imgur.com/"]))').each(function (i) {
    $(this).css('border', '5px solid');
    $(this).remove('a'); // Does NOT work! Nothing happens...
    console.log($(this));
})

Click image below for full size. The marked line is pure coincidence and indicates nothing. To test stuff out, visit http://reddit.com and use Firebug (jQuery is loaded): Firebug screenshot containing part of Reddits DOM

like image 803
Deleted Avatar asked Feb 06 '26 01:02

Deleted


2 Answers

You need to find it, and then remove it:

$(this).find('a').remove();
like image 55
Curtis Avatar answered Feb 08 '26 15:02

Curtis


Provide this as the context:

$("a", this).remove();

The second parameter to the $ function is often times the context for your selector, meaning the area in which you'd like to find matches to your selector. In this particular case, we're saying we'd like to find a elements within this.

jQuery will internally convert this to a find call:

$(this).find("a").remove();

So if you don't mind a slightly more verbose solution (a few chars, no big deal), you can pick up a very negligible performance boost by cutting out the middle-man syntax and using .find directly.

like image 43
Sampson Avatar answered Feb 08 '26 13:02

Sampson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!