74

How can I select a class from that object this?

$(".class").click(function(){
        $("this .subclass").css("visibility","visible");
})

I want to select a $(this+".subclass"). How can I do this with Jquery?

0

6 Answers 6

141

Use $(this).find(), or pass this in context, using jQuery context with selector.

Using $(this).find()

$(".class").click(function(){
     $(this).find(".subclass").css("visibility","visible");
});

Using this in context, $( selector, context ), it will internally call find function, so better to use find on first place.

$(".class").click(function(){
     $(".subclass", this).css("visibility","visible");
});
1
  • 1
    If find() is being called internally in the second method, why are you still calling it manually? Mar 28, 2016 at 13:57
26

Maybe something like: $(".subclass", this);

5
  • 1
    This is a great alternative. using the context +1
    – iConnor
    Jul 19, 2013 at 12:23
  • 1
    @Connor This is an alternative but not so great. Anyway +1 too
    – A. Wolff
    Jul 19, 2013 at 12:32
  • 1
    I appreciate your opinion @roasted
    – iConnor
    Jul 19, 2013 at 12:47
  • @Connor i mainly said that because using context for child selector was supposed to be deprecated: $('> child',context). This was what appear in previous jquery DOC: >>Note: The $("> elem", context) selector will be deprecated in a future release. Its usage is thus discouraged in lieu of using alternative selectors.<< But this disappear from doc and not concern context equivalent to .find(), so... ;)
    – A. Wolff
    Jul 19, 2013 at 12:55
  • @A.Wolff any news on this, is it still safe to use? Mar 4, 2017 at 0:59
12

Use find()

$(this).find(".subclass").css("visibility","visible");
0
3

What you are looking for is this:

$(".subclass", this).css("visibility","visible");

Add the this after the class $(".subclass", this)

1
  • 1
    This really helped me when trying to animate an SVG for something and find wasn't working how I needed it.
    – Xander
    Sep 9, 2015 at 20:18
1

if you need a performance trick use below:

$(".yourclass", this);

find() method makes a search everytime in selector.

0
1

Well using find is the best option here

just simply use like this

$(".class").click(function(){
        $("this").find('.subclass').css("visibility","visible");
})

and if there are many classes with the same name class its always better to give the class name of parent class like this

$(".parent .class").click(function(){
            $("this").find('.subclass').css("visibility","visible");
    })

Your Answer

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

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