bergman
bergman

Reputation: 185

JQuery add find method dynamically

I get a array with variable length. The first element is always the parent. After him the children to find, to find the children and so on. I need to add find methods dynamically. Or is there a better method.

MyArray:{'.grand_parent','.older_child','.younger_child'} 

generate this:

$(#base).parent('.grand_parent').find('.older_child').find('.younger_child');

What about this array:

LongerArray:{'.grand_parent','.child1','.child2','.child3','child4'}

Upvotes: 2

Views: 92

Answers (1)

Ram
Ram

Reputation: 144689

Assuming the first element of the array should be passed to .parent() method and other elements should be passed to .find() method, there is no need to call several .find() methods, you can .join() the elements and pass the result to the .find() method as one selector:

$('#base').parent(arr[0]) // .parent(".grand_parent")
          .find(arr.slice(1).join(' ')); // .find(".child1 .child2 .child3 .child4")

Note that .parent() method doesn't select grandparent elements, it only selects the first-level parent element of the selected element(if a selector is passed to it, it selects the parent element only if it matches the specified selector), if you want to select parent/grandparent element(s) according to your needs you can use .closest() or .parents() method instead.

Upvotes: 3

Related Questions