21
var parent = $("#jcontent");
var button1 = parent(".button1")

How to select .button1 knowing it is inside the parent while not reusing #jcontent?

I need to do this because I only want to pass the parent as parameter and to be able to cache it which is faster.

HamZa
  • 14,671
  • 11
  • 54
  • 75
Totty.js
  • 15,563
  • 31
  • 103
  • 175

2 Answers2

32

Another alternative

var parent = $("#jcontent"); 
var button1 = $(".button1", parent) ;
Chandu
  • 81,493
  • 19
  • 133
  • 134
  • i like this ;) anyway both are great! I wish I could accept 2 answers xD thanks! – Totty.js Dec 16 '10 at 23:47
  • @JasperMogg The way I see it, this 'works', because this is the way the jQuery API is defined :). The second parameter of the selector expression (the JavaScript variable 'parent' holding a jQuery type value) indicates the scope within which the first parameter (the selector ".button1") is applied. If you leave out the second parameter, as is mostly done, then the default whole document is assumed as the scope to apply the selector. – Bart Jan 07 '14 at 12:50
  • @MuhammadUmer Can you please elaborate? I am not clear about your question. – Chandu Apr 15 '14 at 03:07
  • can you give link to jquery docs where it describes this behavior – Muhammad Umer Apr 15 '14 at 03:28
  • 1
    Check https://api.jquery.com/jquery/#jQuery1 . Look at the description of the context parameter. – Chandu Apr 15 '14 at 13:25
16
var button1 = parent.find(".button1");
Karmic Coder
  • 17,569
  • 6
  • 32
  • 42