JavaScript: Difference Between GetElementByID and QuerySelector (kiru.io) 4 points by kiru_io 2y ago ↗ HN
[–] 6510 2y ago ↗ Interesting difference but why is querySelector(`#${CSS.escape(id)}`) better?I would prefer to use valid id's but also, when selecting by id I just use getElementByID?You could also use querySelectorAll(id) and have more than one element with the same id. It doesn't seem like a good idea. [–] kiru_io 2y ago ↗ > Interesting difference but why is querySelector(`#${CSS.escape(id)}`) better?The linked SO[0] link answers the question: Basically, you can have an id starting with a number, but have to escape them correctly.I was mostly surprised to learn there is a difference between CSS selectors and the querySelector in Javascript.[0] https://stackoverflow.com/a/20306237 [–] 6510 2y ago ↗ I'm mostly surprised we have different rules for id's in html5 and css.That you can hack something up that will accept numbers is no surprise. You could use getAttribute or xpath, I'm sure those will accept numbers too.
[–] kiru_io 2y ago ↗ > Interesting difference but why is querySelector(`#${CSS.escape(id)}`) better?The linked SO[0] link answers the question: Basically, you can have an id starting with a number, but have to escape them correctly.I was mostly surprised to learn there is a difference between CSS selectors and the querySelector in Javascript.[0] https://stackoverflow.com/a/20306237 [–] 6510 2y ago ↗ I'm mostly surprised we have different rules for id's in html5 and css.That you can hack something up that will accept numbers is no surprise. You could use getAttribute or xpath, I'm sure those will accept numbers too.
[–] 6510 2y ago ↗ I'm mostly surprised we have different rules for id's in html5 and css.That you can hack something up that will accept numbers is no surprise. You could use getAttribute or xpath, I'm sure those will accept numbers too.
3 comments
[ 3.4 ms ] story [ 17.8 ms ] threadI would prefer to use valid id's but also, when selecting by id I just use getElementByID?
You could also use querySelectorAll(id) and have more than one element with the same id. It doesn't seem like a good idea.
The linked SO[0] link answers the question: Basically, you can have an id starting with a number, but have to escape them correctly.
I was mostly surprised to learn there is a difference between CSS selectors and the querySelector in Javascript.
[0] https://stackoverflow.com/a/20306237
That you can hack something up that will accept numbers is no surprise. You could use getAttribute or xpath, I'm sure those will accept numbers too.