Ways to access the objects(elements) {getElementbyid()} {querySelector()} {querySelectorAll()}
understanding of {getElementByid()} {querySelector()} {querySelectorAll()}
getElementbyid()-
- As the name suggests here "Element" is in singular form so we will be getting only a single element instead of an array of elements like {getElementsbyTagName}.
This can also be seen as {id} which is unique for every element.
Syntax-
var b = document.getElementById("demo");
Example-
var a=document.getElementbyid("title"); //select the element who's id - title
a.innerHTML = "GoodBye"; //change the element's HTML
querySelector()-
It is similar to the {getElementbyid} because it also targets a particular element from the HTML file.
The
querySelector()
method returns the first element that matches a CSS selector.
It takes only one parameter as input, 'selectors'.
Syntax-
element = document.querySelector(selectors);
Example-
var e=document.querySelector("p"); //it will select the first <p> tag
console.log(e);
querySelectorAll()-
- It is different from {querySelector()} because it selects all the elements(objects) in the HTML file that are present at the same level.
In other words, we can say that they returns all elements that matches a CSS selector(s).
Syntax-
document.querySelectorAll(CSS selectors);
Example-
var c = document.querySelectorAll("li"); //it will select all <li> tags
console.log(c);
Note-
All the CSS properties are written in "camelCase" as there are no '-' between the words. Values are assigned in the form of a string.
Conclusion-
A brief understanding of {getElementByid()} {querySelector()} {querySelectorAll()}.