tElementById() - Web APIs | MDN

  • Skip to main content
  • Skip to search
Document: getElementById() method Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

  • Learn more
  • See full compatibility
  • Report feedback

The getElementById() method of the Document interface returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

If you need to get access to an element which doesn't have an ID, you can use querySelector() to find the element using any selector.

Note: IDs should be unique inside a document. If two or more elements in a document have the same ID, this method returns the first element found.

In this article

  • Syntax
  • Examples
  • Usage notes
  • Specifications
  • Browser compatibility
  • See also

Syntax

jsgetElementById(id)

Note: The capitalization of "Id" in the name of this method must be correct for the code to function; getElementByID() is not valid and will not work, however natural it may seem.

Parameters

id

The ID of the element to locate. The ID is a case-sensitive string which is unique within the document; only one element should have any given ID.

Return value

An Element object describing the DOM element object matching the specified ID, or null if no matching element was found in the document.

Examples

HTML

html<p id="para">Some text here</p> <button>blue</button> <button>red</button>

JavaScript

jsfunction changeColor(newColor) { const elem = document.getElementById("para"); elem.style.color = newColor; } document.querySelectorAll("button").forEach((button) => { button.addEventListener("click", (event) => { changeColor(event.target.textContent.toLowerCase()); }); });

Result

Usage notes

Unlike some other element-lookup methods such as Document.querySelector() and Document.querySelectorAll(), getElementById() is only available as a method of the global document object, and not available as a method on all element objects in the DOM. Because ID values must be unique throughout the entire document, there is no need for "local" versions of the function.

Example

html<div id="parent-id"> <p>hello word1</p> <p id="test1">hello word2</p> <p>hello word3</p> <p>hello word4</p> </div> jsconst parentDOM = document.getElementById("parent-id"); const test1 = parentDOM.getElementById("test1");

If there is no element with the given id, this function returns null. Note that the id parameter is case-sensitive, so document.getElementById("Main") will return null instead of the element <div id="main"> because "M" and "m" are different for the purposes of this method.

Elements not in the document are not searched by getElementById(). When creating an element and assigning it an ID, you have to insert the element into the document tree with Node.insertBefore() or a similar method before you can access it with getElementById():

jsconst element = document.createElement("div"); element.id = "test"; const el = document.getElementById("test"); // el will be null!

In non-HTML documents, the DOM implementation must have information on which attributes are of type ID. Attributes with the name "id" are not of type ID unless so defined in the document's DTD. The id attribute is defined to be of ID type in the common cases of XHTML, XUL, and others. Implementations that do not know whether attributes are of type ID or not are expected to return null.

Specifications

Specification
DOM# ref-for-dom-nonelementparentnode-getelementbyid②

Browser compatibility

See also

  • Document reference for other methods and properties you can use to get references to elements in the document.
  • Document.querySelector() for selectors via queries like 'div.myclass'
  • Document.evaluate() - has a utility method for selecting by xml:id in XML documents

Help improve MDN

Was this page helpful to you? Yes No Learn how to contribute

This page was last modified on Jun 3, 2025 by MDN contributors.

View this page on GitHub • Report a problem with this content Filter sidebar
  1. Document Object Model (DOM)
  2. Document
  3. Constructor
    1. Document()
  4. Instance properties
    1. activeElement
    2. activeViewTransition
    3. adoptedStyleSheets
    4. alinkColor Deprecated
    5. all Deprecated
    6. anchors Deprecated
    7. applets Deprecated
    8. bgColor Deprecated
    9. body
    10. characterSet
    11. childElementCount
    12. children
    13. compatMode
    14. contentType
    15. cookie
    16. currentScript
    17. customElementRegistry
    18. defaultView
    19. designMode
    20. dir
    21. doctype
    22. documentElement
    23. documentURI
    24. domain Deprecated
    25. embeds
    26. featurePolicy Experimental
    27. fgColor Deprecated
    28. firstElementChild
    29. fonts
    30. forms
    31. fragmentDirective
    32. fullscreen Deprecated
    33. fullscreenElement
    34. fullscreenEnabled
    35. head
    36. hidden
    37. images
    38. implementation
    39. lastElementChild
    40. lastModified
    41. lastStyleSheetSet Non-standard Deprecated
    42. linkColor Deprecated
    43. links
    44. location
    45. pictureInPictureElement
    46. pictureInPictureEnabled
    47. plugins
    48. pointerLockElement
    49. preferredStyleSheetSet Non-standard Deprecated
    50. prerendering Experimental
    51. readyState
    52. referrer
    53. rootElement Deprecated
    54. scripts
    55. scrollingElement
    56. selectedStyleSheetSet Non-standard Deprecated
    57. styleSheets
    58. styleSheetSets Non-standard Deprecated
    59. timeline
    60. title
    61. URL
    62. visibilityState
    63. vlinkColor Deprecated
    64. xmlEncoding Deprecated
    65. xmlVersion Deprecated
  5. Static methods
    1. parseHTML() Experimental
    2. parseHTMLUnsafe()
  6. Instance methods
    1. adoptNode()
    2. append()
    3. ariaNotify() Experimental
    4. browsingTopics() Non-standard Deprecated
    5. caretPositionFromPoint()
    6. caretRangeFromPoint() Non-standard
    7. clear() Deprecated
    8. close()
    9. createAttribute()
    10. createAttributeNS()
    11. createCDATASection()
    12. createComment()
    13. createDocumentFragment()
    14. createElement()
    15. createElementNS()
    16. createEvent() Deprecated
    17. createExpression()
    18. createNodeIterator()
    19. createNSResolver() Deprecated
    20. createProcessingInstruction()
    21. createRange()
    22. createTextNode()
    23. createTouch() Non-standard Deprecated
    24. createTouchList() Non-standard Deprecated
    25. createTreeWalker()
    26. elementFromPoint()
    27. elementsFromPoint()
    28. enableStyleSheetsForSet() Non-standard Deprecated
    29. evaluate()
    30. execCommand() Deprecated
    31. exitFullscreen()
    32. exitPictureInPicture()
    33. exitPointerLock()
    34. getAnimations()
    35. getElementById()
    36. getElementsByClassName()
    37. getElementsByName()
    38. getElementsByTagName()
    39. getElementsByTagNameNS()
    40. getSelection()
    41. hasFocus()
    42. hasPrivateToken() Experimental
    43. hasRedemptionRecord() Experimental
    44. hasStorageAccess()
    45. hasUnpartitionedCookieAccess()
    46. importNode()
    47. moveBefore()
    48. mozSetImageElement() Non-standard
    49. open()
    50. prepend()
    51. queryCommandEnabled() Non-standard Deprecated
    52. queryCommandState() Non-standard Deprecated
    53. queryCommandSupported() Non-standard Deprecated
    54. querySelector()
    55. querySelectorAll()
    56. releaseCapture() Non-standard
    57. replaceChildren()
    58. requestStorageAccess()
    59. requestStorageAccessFor() Experimental
    60. startViewTransition()
    61. write() Deprecated
    62. writeln() Deprecated
  7. Events
    1. afterscriptexecute Non-standard Deprecated
    2. beforescriptexecute Non-standard Deprecated
    3. DOMContentLoaded
    4. fullscreenchange
    5. fullscreenerror
    6. pointerlockchange
    7. pointerlockerror
    8. prerenderingchange Experimental
    9. readystatechange
    10. scroll
    11. scrollend
    12. scrollsnapchange Experimental
    13. scrollsnapchanging Experimental
    14. securitypolicyviolation
    15. selectionchange
    16. visibilitychange
  8. Inheritance
    1. Node
    2. EventTarget
  9. Related pages for DOM
    1. AbortController
    2. AbortSignal
    3. AbstractRange
    4. Attr
    5. CDATASection
    6. CharacterData
    7. Comment
    8. CustomEvent
    9. DOMError Deprecated
    10. DOMException
    11. DOMImplementation
    12. DOMParser
    13. DOMTokenList
    14. DocumentFragment
    15. DocumentType
    16. Element
    17. Event
    18. EventTarget
    19. HTMLCollection
    20. MutationObserver
    21. MutationRecord
    22. NamedNodeMap
    23. Node
    24. NodeIterator
    25. NodeList
    26. ProcessingInstruction
    27. QuotaExceededError Experimental
    28. Range
    29. ShadowRoot
    30. StaticRange
    31. Text
    32. TreeWalker
    33. XMLDocument
    34. XPathEvaluator
    35. XPathExpression
    36. XPathResult
    37. XSLTProcessor
  10. Guides
    1. Anatomy of the DOM
    2. Attribute reflection
    3. Selection and traversal on the DOM tree
    4. Building and updating the DOM tree
    5. Working with events

Tag » What Is Getelementbyid In Javascript