JQuery solution between children () and find (): everything that looks like near ()?

Based on the answers received, the only solution using jQuery without implementing our own select function is a basic selector with ": first" or followed by ".eq (0)" for jQuery.

I wanted to know if they have any maximum depth parameter or a function like “get only the first result and then return it”, but it seems that it is not available in jQuery, because even: at first, it seems there is no faster in the selector, than calling .eq (0) Thanks for all the comments.


Original post:

I am wondering if the closest function is available for child elements.

Say I have an html structure like this:

div.container> [* some elements, I cannot use children ()]> div.sub1> div.sub2> div.sub1> [other various child elements]

If I want the first div.sub1, I do something like:

$("div.container").find("div.sub1").eq(0) 

The problem is that we cannot specify the "maximum depth", so it will be searched for in ALL child elements. I see this as a performance issue.

I'm talking about "maximum depth" because I can list the cases for selecting selectors, but it will be a long list, about 6-10 elements, depending on the case.

Does anyone have a solution for this?

thanks

+4
source share
1 answer

You can get this by combining the child selector ( > ) and the wildcard ( * ) in different quantities:

 // max-depth: grand-children $('.container').find('> .sub1, > * > .sub1').first(); // max-depth: great-grand-children $('.container').find('> .sub1, > * > .sub1, > * > * > .sub1').first(); 

And, since this can be quite tedious for hard coding, you can use your own method to create a selector for you:

 jQuery.fn.findAtDepth = function (selector, maxDepth) { var depths = [], i; if (maxDepth > 0) { for (i = 1; i <= maxDepth; i++) { depths.push('> ' + new Array(i).join('* > ') + selector); } selector = depths.join(', '); } return this.find(selector); }; $('.container').findAtDepth('.sub1', 3).first(); 

Exam: http://jsfiddle.net/V82f3/2/


The main disadvantage of this is that it is limited to relatively simple selectors (or, perhaps, only individual selectors):

 $('.container').findAtDepth('.sub1, .sub2', 3).first(); 

This will search for .sub1 at a maximum depth of 3, but for .sub2 at any depth.

+7
source

Source: https://habr.com/ru/post/1393016/


All Articles