loading...

Discussion on: Generate and Set Pseudorandom Hexadecimal Background Color Using JavaScript

Collapse
somedood profile image
Basti Ortiz (Some Dood)

This is a great read for beginners. I also wondered how to make a random color generator before in my early days.

Also, you don't need to add an id to the <body> tag; you can directly refer to it by writing document.body. 😉

Collapse
nickfazzpdx profile image
Nicholas Fazzolari Author

Thanks for the heads up. Does using id's to link js to the DOM hurt performance (at scale)?

Collapse
somedood profile image
Basti Ortiz (Some Dood)

Yes, it's definitely going to hurt performance at scale. Though you shouldn't worry about too much unless it's completely necessary to optimize and squeeze every single bit of efficiency for your CPU.

Optimization is good, but as soon as you allow it to become premature optimization, that's when you should reconsider your priorities. You wouldn't want to allow the latter to get in the way of making actual progress in software development.

Collapse
antjanus profile image
Antonin Januska

I saw a tweet about this last week! Using document.querySelector('body') is actually more performant than using document.body. So I wonder if doing document.querySelector('#some-id') would still be faster than document.body! :)

Thread Thread
somedood profile image
Basti Ortiz (Some Dood)

I wonder if there's a jsPerf for that by now. I'm really curious to see which method is more performant.

Collapse
chiff profile image
Chiffre

TL;DR - you don't want to use that

@dood also every #ID is in DOM is accessible via window[id] however it's diacouraged to use that because it was implemnted in browsers due historic and compatibility reasons. More info here. It can be removed in future and make your page not working. Check answers and comments too. What I wanted to say is that window.body could be accessible because of same reason (I'm not sure).

Collapse
somedood profile image
Basti Ortiz (Some Dood)

Oh, wow. I never even knew that you could access an id from the window object. Thanks for making me learn something new today! I am genuinely surprised and amused by this.