Edit Template
  • Home
  • /
  • JS getElementbyId
Edit Template
  • Home
  • /
  • JS getElementbyId

JavaScript getElementById() Method

The getElementById() method is one of the most commonly used ways to select elements in JavaScript. It allows you to directly target an HTML element by its unique id attribute.

Syntax

				
					document.getElementById("id");

				
			
  • "id" is the exact string of the element’s id.

  • The method returns the element if found, or null if no element with that ID exists.

  • It is case-sensitive.

Example HTML

				
					<div id="notice">Original content</div>

				
			

Example JavaScript Usage

				
					let box = document.getElementById("notice");
box.innerHTML = "Updated by Learn With Arshyan!";

				
			

This changes the content of the element with ID "notice".

Important Notes

  • The id must be unique on the page. If multiple elements share the same ID (which is invalid HTML), only the first one is returned.

  • The method is case-sensitive: "Notice" and "notice" are treated as different.

Conclusion

The getElementById() method is the fastest and most direct way to access an element in the DOM. It’s essential for building interactive and dynamic pages, such as updating content, styling elements, or triggering animations.

Master this method, and you’ll have solid control over your page content.

Scroll to Top