jQuery: find() children until a certain threshold element is encountered

前端 未结 4 1319
不思量自难忘°
不思量自难忘° 2021-02-19 17:59

I have a nested table structure like

   
4条回答
  •  你的背包
    2021-02-19 18:38

    I had a similar issue and was still challenged to do something without an extension loop or having the exact structure of the DOM. In my case I had already a reference to the element '#first' which if you don't we could get it for example with an each (even if it is only one object). The trick is to go back up the tree with parentsuntil and stop at your top element to see if there is any intermediate element satisfying the conditionn.

    Using the shorthand lambda notation for the functions (as you can write in typescript) this would lead to this:

    $('#first').each((idx, f) => $(f).find('input').filter((idx2, inp) => $(inp).parentsUntil(f, 'table').length == 0)
    

    It might not be the most efficient way (as you first select everything to then throw away elements by mounting up the DOM-tree again, but it is compact and fairly generic.

提交回复
热议问题