16

I have the following code :

$('.TopNotificationIcon span').remove();    

Can I replace .TopNotificationIcon with this i.e only span exists inside this specific class.

This is the structure

<div class="TopNotificationIcon"><span>xxxxx</span></div>

On click of .TopNotificationIcon, span should be removed.

1
  • 2
    not sure to understand exactly what you want? Do you want to test if a span is under a certain class or remove all span under TopNotification in a function? Commented May 24, 2011 at 15:13

5 Answers 5

19

if you have click event for .TopNotificationIcon you can do something like this

$('.TopNotificationIcon').click(function(){
    $('span',this).remove();    
});
1
  • my error was different but community claims this to be correct. so thanks for the tip hoping it's correct no time to check it out Commented Jun 1, 2011 at 11:44
15

I would use the find() method, as it seems to be the fastest:

$("div.TopNotificationIcon").click(function() {

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

});
5
  • The context used by @TheSuperTramp is just a shorthand to find().
    – kapa
    Commented May 24, 2011 at 15:22
  • Yes, but that just turns around and does a find(), does it not? So, wouldn't it be more prudent to just use find() directly? Commented May 24, 2011 at 15:33
  • The difference is so minimal that you should use the one that is more readable and logical to you :).
    – kapa
    Commented May 24, 2011 at 20:07
  • @bazmegakapa - The gurus that I listen to always say that find() > context. I know what you are saying, but what is minimal in the simplest form, could be larger in a complex form. So removing an extra operation could be noticeable. Commented May 24, 2011 at 20:26
  • 1
    That's the kind of micro-optimization my gurus keep me away from.
    – kapa
    Commented May 24, 2011 at 21:24
4

If you want to remove all span under TopNotification you can do this :

$('div').live('click', function(){
    $(this).children('span').remove();    
});

It will remove all children in a div.

1
  • This is unnecessarily verbose. $('.TopNotificationIcon span').remove(); is quite enough.
    – kapa
    Commented May 24, 2011 at 15:21
3

Yes but youd need to change the line to:

$(this).children('span').remove();

js fiddle: http://jsfiddle.net/UNhhh/1/

2

Try this...

$('span').remove('.TopNotificationIcon');

This will remove all span elements with the class TopNotificationIcon and also child elements

1
  • This is not what the OP wanted. .TopNotificationIcon is one of the parents of the span to be removed.
    – kapa
    Commented May 24, 2011 at 15:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.