How to get an element by ID in JavaScript

Getting elements by ID is the most direct way to select specific HTML elements for manipulation, styling, or event handling. As the creator of CoreUI, a widely used open-source UI library, I’ve used element selection extensively for interactive component functionality. From my expertise, document.getElementById() is the fastest and most reliable method for selecting elements with unique IDs. This approach provides direct access to specific elements without the overhead of more complex selectors.

Use document.getElementById() to select an element by its unique ID attribute.

const element = document.getElementById('myButton')
element.textContent = 'Click me!'

Here document.getElementById('myButton') searches the DOM for an element with id="myButton" and returns a reference to that element. Once you have the element reference, you can modify its properties, add event listeners, or manipulate its content. This method returns null if no element with the specified ID exists.

Best Practice Note:

IDs must be unique within a document, making this method highly efficient. Always check if the element exists before manipulation to avoid errors. This is the same approach we use in CoreUI components for targeting specific interactive elements.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
Mastering Inline Styles in React.js: Enhancing Your Components with Style
Mastering Inline Styles in React.js: Enhancing Your Components with Style

How to Clone an Object in JavaScript
How to Clone an Object in JavaScript

Understanding the Difference Between NPX and NPM
Understanding the Difference Between NPX and NPM

How to Remove Underline from Link in CSS
How to Remove Underline from Link in CSS

Answers by CoreUI Core Team