4 ms·
The class related functions have been made native by the classList property of elements. element.classList.has('someClass') //true if present element.c
by ehnto 6y ago
The class related functions have been made native by the classList property of elements.
element.classList.has('someClass') //true if present
element.classList.add('someClass') //add to element
element.classList.remove('someClass') //remove from element
element.classList.toggle('someClass') //remove if present, add if not present
I would also argue element.querySelector and element.querySelectorAll are plenty shorthand to replace the selector helpers!
Not saying HN should rewrite their JS obviously, just for anyone reading this and wondering if there are native equivalents.
- yesenadam 6y agoThanks you! I was hoping someone would spell out the "changes from the last 5 years" mentioned elsewhere.
- rasz 6y agoquerySelectorAll is a lot slower than old school functions. You would be tempted to say who cares, but then you load Gmail and wait 2 seconds for UI to render.
- kevincox 6y agoDo you have any references for this? I would be flabbergasted if the simple case of #id and .class weren't optimized to be basically identical. (the only difference being that they had to do a quick "parse" before jumping into the optimized path)
- rasz 6y agohttps://jsperf.com/getelementbyid-vs-queryselector/25 https://jsperf.com/getelementbyid-vs-queryselector/25 tldr just looking for class x10 slower.
- kevincox 6y agoTrying that on Firefox mobile and they are all within 5%. The direct calls are faster but that could conceivably be the time to check for special cases with a DOM that small.
- albedoa 6y agohttps://www.sitepoint.com/optimizing-css-id-selectors-and-other-myths/ https://www.sitepoint.com/optimizing-css-id-selectors-and-ot... The slowest and most convoluted selector took 21ms when tested against 50,000 elements using a 2014 MacBook Pro.
- rasz 6y ago20ms for one call over 50000 elements, on a 2.6GHz cpu capable of 4 IPC. 50-200K instructions per element. Truly we are living in the future :)