![]() |
In JavaScript, both document.querySelector() and document.getElementById() are methods used to select elements from the DOM. They serve similar purposes but have differences in their usage and capabilities. What is document.querySelector()?The document.querySelector() is a method that allows to the select a single element in the DOM using a CSS selector. It returns the first element that matches the specified CSS selector within the document. Syntax:document.querySelector(selector) Example: In this example, document.querySelector(‘.text’) selects the first element with the class “text” and logs its text content to the console.
Output: The output will be in the console of your browser. Hello, World! What is document.getElementById()?The document.getElementById() is a method that allows to select a single element in the DOM using its unique ID attribute. It returns the element with the specified ID. Syntax:document.getElementById(id) Example: In this example, document.getElementById(‘message’) selects the element with ID “message” and logs its text content to the console.
Output: The output will be in the console of your browser. Hello, World! Difference Between JavaScript document.querySelector() and document.getElementById()
ConclusionBoth document.querySelector() and document.getElementById() are essential methods for the selecting elements from the DOM in JavaScript. While querySelector() offers more flexibility with the CSS selectors getElementById() is optimized for the selecting elements by their IDs providing better performance. Choose the appropriate method based on the specific requirements and compatibility needs. |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |