![]() |
In JavaScript, we can use the “id” attribute to interact with HTML elements. The “id” attribute in HTML assigns a unique identifier to an element. This uniqueness makes it easy for JavaScript to precisely target and manipulate specific elements on a webpage. Selecting elements by ID helps in dynamic content updates, event handling, and DOM manipulation. Table of Content Using getElementById methodJavaScript hase Syntax:let element = document.getElementById("myElement");
Example: To demonstrate selecting an HTML element by ID in JavaScript and then using it for updating the state of another HTML element. HTML
Output: Using the query selector methodThe querySelector method is a more flexible and versatile approach to element selection. In this case, the CSS selector #myElement targets the element with the specified ID. While querySelector is powerful, it’s essential to note that if multiple elements share the same ID, it will only return the first one encountered in the document. Syntax:let element = document.querySelector("#myElement");
Example: This HTML example creates a webpage with a heading and a button. Clicking the button triggers a JavaScript function that changes the text color of the heading to blue. HTML
Output: |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |