1

I have an element #xxx and I have to select all children (any level) and all parent of this element. I dont want to select the element itself.

So far I've been using this jquery code but I am pretty sure there must be a way to make this more efficiently (maybe using addBack):

$("#xxx").find("*").add($("#xxx").parents())

Do you suggest any other alternative that does not make use of add() cause I think this selector is not efficient cause it queries internally again the #xxx. I think using addBack() would be nicer cause it does not cause another search for the element #xxx.

Samul
  • 1,824
  • 5
  • 22
  • 47
  • Have you tried using something like ":not(#xxx)" – hallleron Aug 25 '17 at 13:30
  • Where should I put `:not`? In the code I provided there is no need to use `:not`, it already works but I think it's not efficient because it has to query twice for the element #xxx – Samul Aug 25 '17 at 13:36
  • This is a rather odd requirement. Could you explain why you need this, as there may be a better approach – Rory McCrossan Aug 25 '17 at 13:40
  • @RoryMcCrossan I am running this code for a while in the "scroll" event. Dont worry, I am using a combination of setTimeout/clearTimeout to avoid firind my custom function every time "onscroll" is fired. Anyway, after tracking what was not causing a smooth scroll I realized it was this selector that I posted here. If I remove this selector and replace it with a simpler thing the scroll gets very smooth. I already used request animation frames but it does not work well on older browser.... so yeah, I am stuck with this problem. – Samul Aug 25 '17 at 13:52
  • just use `$(':not(#xxx)')` and it will return what you want – Koushik Chatterjee Aug 25 '17 at 13:54
  • @KoushikChatterjee it will return siblings... I dont want siblings nor their children. I want only the parents and children of my `#xxx` element. – Samul Aug 25 '17 at 13:55

1 Answers1

1

First time answering, please let me know if this is not the right way to do it.

But this is not a direct answer to your original question, but rather to your problem that you mentioned in the comments:

If I remove this selector and replace it with a simpler thing the scroll gets very smooth.

Since you are reusing the selector reference, perhaps you can store the selector, $('#xxx'), as a variable. Since the initial lookup is the heaviest part of the selector.

const $xxx = $('#xxx');
$xxx.find("*").add($xxx.parents())

Performance of jQuery selectors vs local variables

petern-sc
  • 76
  • 1
  • 5
  • Yeap that helps, indeed jquery caches the elements returned! I can see a sensible improvement in the scroll. I will upvote your answer and if no better answer gets sent I will approve it, thanks my friend. – Samul Aug 25 '17 at 15:30
  • Sorry for taking so long to accept your answer, realy sorry. I got flu and stayed in bed for a few days. Thans for helping. – Samul Sep 04 '17 at 01:52