Hacker News new | past | comments | ask | show | jobs | submit login

Other functions are much more difficult to replace

    $('.sth').closest('ul')
To me jQuery is like Regex or Linq. I think it had a really good api.




Is not the same thing as it is a Element method, not NodeList one, so you will would need to map it instead. Because NodeList doesn't have the .map method you would also need to transform it to a Array first.

So the actually drop-in replacement of `$(foo).closest(bar)` would be something like:

    Array.from(document.querySelector(foo)).map(el => el.closest(bar))


This did not exist the last time I looked. TIL. Thank you!


Is it harder or just a bit longer-winded? E.g. i'm thinking this is the same behaviour

    document.getElementsByClassName('sth')[0]?.closest('ul');


That's not exactly the same, I don't think, because jQuery will give you all the `ul` that are closest to `.sth`, not just the first. You'd have to write a loop over the list returned from `document.getElementsByClassName('sth')` to get the same behaviour (because it doesn't look like the standardised `closest` works on lists.)


If i'm following right, i think this expression would match?

    Array.from(document.getElementsByClassName("sth")).map(e => e.closest("ul"))
The jQuery is definitely nicer to read than this though


Yeah, that seems to do the same.


Thanks, this is now standard it seems. TIL




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: