56 AnswersNew Answer
Hi guys! What exactly does document.querySelector() and document.querySelectorAll() do? I've checked online but I'm yet to find a `dumbed-down` explanation of them. Can someone please explain with examples?
8/13/2020 10:16:22 AM👑 Tchybooxuur![Inactive]
56 AnswersNew Answer
There is no document.querySelectors it is querySelectorAll. querySelector selects the first element that matches a CSS selector. querySelectorAll returns a collection of all elements that matches a CSS selector. EDIT: Wow. I never expected this much upvotes. 😄 Thanks everyone
If you are known to css then it is a very easy task! document.querySelector("#haha") Is same as document.getElementById("haha") And document.querySelectorAll(".haha") Is same aa document.getElementsByClassName("haha")
Hey 👑Tchybooxuur! I created this small code to demonstrate the difference. https://code.sololearn.com/W0Gjy3PZbM6X
Ore It would help a great deal if you could explain what each line of your JS code does. Perhaps by way of commenting or by any other way you deem fit. You could totally do it whenever you are chanced.
Ore Thanks. Let me edit accordingly 👍🏼
Namit Jain Whoa! Thanks men 👍🏼
Thanks Ore Checking it out right away!
👑Tchybooxuur! Sorry about that. I did not write it with the intention that it will be read. I expected you to just check the output and see what is returned by the two functions. Anyway, I will try to simplify the code. Pardon me.
👑Tchybooxuur! You can check it now
Ore maybe due to many friends 😂😅👦 Cuz he is a very friendly guy
That's what's up Ore I'm a very friendly guy! ☺️☺️☺️ Thanks Namit Jain 👌
Namit Jain Yeah. Maybe
Kode Krasher Haha. A champion for writing an unreadable code that the OP could not even understand? I feel ashamed rn
Ore 😂 That's entirely the fault of the OP. You did noble... 👍🏼
Kode Krasher I checked his profile and he's helped virtually everyone on sololearn with a web related question. He's that hot 🔥 upstairs! 😅😅😅
Kode Krasher: Very well said... 👍🏼
Kode Krasher and 👑Tchybooxuur! Thanks 😊
Jorat For the most part you are right except that `querySelectorAll` returns a NodeList not an array. A NodeList is also iterable like an array but does not have the array methods like reduce, filter.
junayeD ●_° Thanks a lot. You did a great job simplifying things. I have a further question not necessarily related to the above question. How would you write your function so that on clicking the button multiple times, it toggles between the new value and the initial value? Like if I press the button once, background turns red and when I press again, it goes back to white like so.
SoloLearn Inc.4 Embarcadero Center, Suite 1455
Send us a message