New course! Every coder should learn Generative AI!
Try a free lesson0
Would like to know about 'querySelector()'..
Would you please help me to learn query selector.. although I've already completed the Javascript course.. but I didn't get any lesson on it.. I know I could Google it but would like to hear from sololearners.. thank you
7 Answers
+ 2
Ok so you want to know the difference between getElementById or getElementByClassName and querySelector:
querySelector uses CSS selectors to take an element from the DOM
getElementById can only select one element from the DOM. getElementByClassName and querySelector can select various elements.
getElementByClassName returns a lista with all elements that match with the given class (it happens the same if querySelector selects classes)
Hope this is helpful
+ 2
querySelector is used for taking elements from the DOM (as you probably know)
You can use it for selecting classes
var obj = document.querySelector(“.title”)
If there are some objects with the same class:
var obj2 = document.querySelector(“.title”)[1] -> Second element with class title
You can also do the same with ids:
var obj = document.querySelector(“#title”)
And you can use querySelectorAll for selecting various elements:
var obj = document.querySelectorAll(“.title”) -> All elements with class title
You can use querySelector for taking, for example, links:
let link = document.querySelector('a[href*="https://google.com"]');
+ 2
What do you mean? Isnt my answer working?
+ 1
Ugulberto Sánchez Thank you for your reply..as we know that literally We use to select an element using document.getElementbyId or class or tag.. but when I try out with It doesn't bring any result.. It's also an way to select element right?
+ 1
Ugulberto Sánchez THANK YOU SO MUCH. I GOT IT NOW.
+ 1
Sony Hossain Yw :)
0
Yeah of course.. please don't get heated.. just wanted to know the difference between those.. thank you..