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?

zurfyx
  • 31,043
  • 20
  • 111
  • 145

6 Answers6

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");
});
Adil
  • 146,340
  • 25
  • 209
  • 204
26

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

Kamil
  • 782
  • 1
  • 6
  • 22
  • 1
    This is a great alternative. using the context +1 – iConnor Jul 19 '13 at 12:23
  • 1
    @Connor This is an alternative but not so great. Anyway +1 too – A. Wolff Jul 19 '13 at 12:32
  • 1
    I appreciate your opinion @roasted – iConnor Jul 19 '13 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 '13 at 12:55
  • @A.Wolff any news on this, is it still safe to use? – Hastig Zusammenstellen Mar 04 '17 at 00:59
12

Use find()

$(this).find(".subclass").css("visibility","visible");
techfoobar
  • 65,616
  • 14
  • 114
  • 135
3

What you are looking for is this:

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

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

chiwangc
  • 3,566
  • 16
  • 26
  • 32
Gabriel Comeau
  • 145
  • 1
  • 2
  • 1
    This really helped me when trying to animate an SVG for something and find wasn't working how I needed it. – Xander Sep 09 '15 at 20:18
1

if you need a performance trick use below:

$(".yourclass", this);

find() method makes a search everytime in selector.

Matricore
  • 575
  • 7
  • 12
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");
    })
Sandeep Gantait
  • 837
  • 8
  • 9