0

I working on this code currently

var cctypeid = $(this).attr("id");
var data = $.parseJSON($("#"+cctypeid+"-id").val());
    $.each(data, function (index, item) {

    });

Inside the .each() I need to populate the form field indicated by index.

Two questions:
1) Is something like this more efficient $("#myForm #myField") than $("#myField") in this scenario or any scenario for that matter?

2) If I do the former, but want to cache $("#myForm) with var _myform = $("#myForm) how do I then write the call? Does the caching in this scenario make sense?

Ok, more than 2 questions.

Thanks,
Derek

3
  • For 2), try $("#myField", _myform). Commented Oct 3, 2014 at 15:15
  • $("#myField") > $("#myForm #myField") Commented Oct 3, 2014 at 15:15
  • Firstly, IDs must be unique on a page to be valid HTML. Secondly, browsers cache a fast lookup of elements by ID. Adding a second ID is slower as you are adding a check that the element's ancestors include the second ID. Commented Oct 3, 2014 at 15:24

1 Answer 1

1

No, it's not more efficient to have two identities in the selector instead of one. On the contrary, if you have two identities, the browser has to check that the element with the second identity is actually inside an element with the first identity.

(There is a difference in function there, of course. If you actually only want the element to be found if it is inside another element (for example if the code should work for different pages), then naturally you need both identities.)

If you want to use an element as scope for a search (for some other reason), you can use the find method:

var frm = $("#myForm");
var field = frm.find("#myField");

or you can use the element as context in the jQuery call:

var frm = $("#myForm");
var field = $("#myField", form);
2
  • Please note that if OP care about performance (since his main question is all about that), .find is faster than $(selector, context). Commented Oct 3, 2014 at 15:16
  • Thanks to both of you. Helps me out.
    – dbinott
    Commented Oct 3, 2014 at 15:24

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