diff --git a/files/en-us/web/api/document/getelementbyid/index.md b/files/en-us/web/api/document/getelementbyid/index.md index 58b6761e8ee40cd..bfeecb234a1b77a 100644 --- a/files/en-us/web/api/document/getelementbyid/index.md +++ b/files/en-us/web/api/document/getelementbyid/index.md @@ -17,20 +17,24 @@ browser-compat: api.Document.getElementById {{ ApiRef("DOM") }} -The {{domxref("Document")}} method **`getElementById()`** returns an {{domxref("Element")}} object representing the element whose {{domxref("Element.id", "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. +The **`getElementById()`** method of the {{domxref("Document")}} interface returns an {{domxref("Element")}} object representing the element whose {{domxref("Element.id", "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 {{domxref("Document.querySelector", "querySelector()")}} to find the element using any {{Glossary("CSS selector", "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. + ## Syntax ```js-nolint getElementById(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 case-sensitive string which is unique within the document; only one element may have any given 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 @@ -68,8 +72,6 @@ function changeColor(newColor) { ## Usage notes -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. - Unlike some other element-lookup methods such as {{domxref("Document.querySelector()")}} and {{domxref("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 @@ -100,7 +102,7 @@ Unlike some other element-lookup methods such as {{domxref("Document.querySelect 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 `
` 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 {{domxref("Node.insertBefore()")}} or a similar method before you can access it with `getElementById()`: +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 {{domxref("Node.insertBefore()")}} or a similar method before you can access it with `getElementById()`: ```js const element = document.createElement('div'); @@ -108,7 +110,7 @@ element.id = 'testqq'; const el = document.getElementById('testqq'); // el will be null! ``` -**Non-HTML documents**. The DOM implementation must have information that says 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](/en-US/docs/Glossary/XHTML), XUL, and other. Implementations that do not know whether attributes are of type ID or not are expected to return `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](/en-US/docs/Glossary/XHTML), XUL, and others. Implementations that do not know whether attributes are of type ID or not are expected to return `null`. ## Specifications diff --git a/files/en-us/web/api/documentfragment/getelementbyid/index.md b/files/en-us/web/api/documentfragment/getelementbyid/index.md new file mode 100644 index 000000000000000..479f52544610b63 --- /dev/null +++ b/files/en-us/web/api/documentfragment/getelementbyid/index.md @@ -0,0 +1,130 @@ +--- +title: DocumentFragment.getElementById() +slug: Web/API/DocumentFragment/getElementById +page-type: web-api-instance-method +browser-compat: api.DocumentFragment.getElementById +--- + +{{ ApiRef("DOM") }} + +The **`getElementById()`** method of the {{domxref("DocumentFragment")}} returns an {{domxref("Element")}} object representing the element whose {{domxref("Element.id", "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 {{domxref("Document.querySelector", "querySelector()")}} to find the element using any {{Glossary("CSS selector", "selector")}}. + +> **Note:** IDs should be unique inside a document fragment. If two or more elements in a document fragment have the same ID, this method returns the first element found. + +## Syntax + +```js-nolint +getElementById(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 fragment: only one element should have any given ID. + +### Return value + +An {{domxref("Element")}} object describing the DOM element object matching the specified ID, or `null` if no matching element was found in the document fragment. + +## Examples + +### Extend a list of elements + +In this example, the document contains a list with a single item `Cherry`. We also create a document fragment containing four more items, `Apple`, `Orange`, `Banana`, and `Melon`. + +We then log the result of using `getElementById()` to look for `Apple` and `Cherry` in the document and in the fragment. At this point, `Cherry` appears only in the document while `Apple` appears only in the fragment. + +If you click "Add fragment to document", we append the fragment to the list inside the document, and again log the result of looking for both `Apple` and `Cherry` in the document and in the fragment. This time, both `Apple` and `Cherry` appear in the document, and neither appear in the fragment. + +This is because appending a fragment to a document moves the fragment's nodes into the DOM, leaving behind an empty `DocumentFragment`. + +#### HTML + +```html + +
+List content: + +Fragment content: + +Current status: +
+```
+
+```css hidden
+button {
+  margin-bottom: 10px;
+}
+```
+
+#### JavaScript
+
+```js
+// Create the document fragment with its initial content
+const fragment = new DocumentFragment();
+["Apple", "Orange", "Banana", "Melon"].forEach((fruit) => {
+  const li = document.createElement("li");
+  li.textContent = fruit;
+  li.id = fruit;
+  fragment.append(li);
+});
+
+// When the button is clicked, add the fragment to the list
+document.getElementById("add").addEventListener("click", () => {
+  document.querySelector("ul").append(fragment);
+  displayStatus();
+});
+
+// Log the results of both getElementById()
+function displayStatus() {
+  const log = document.getElementById("log");
+  log.textContent = "";
+  ["Apple", "Cherry"].forEach((id) => {
+    log.textContent += `document.getElementById("${id}") ${
+      document.getElementById(id) ? "Yes" : "No"
+    }\n`;
+    log.textContent += `fragment.getElementById("${id}") ${
+      fragment.getElementById(id) ? "Yes" : "No"
+    }\n`;
+  });
+
+  // Empty the fragment viewer and fill it with the current content
+  const fragmentViewer = document.getElementById("fragment");
+  while (fragmentViewer.hasChildNodes()) {
+    fragmentViewer.removeChild(fragmentViewer.lastChild);
+  }
+  for (entry of fragment.children) {
+    fragmentViewer.appendChild(entry.cloneNode(true));
+  }
+}
+
+// Log the initial state
+displayStatus();
+
+// Hook the reset button
+document.getElementById("reset").addEventListener("click", () => {
+  document.location.reload();
+});
+```
+
+#### Result
+
+{{EmbedLiveSample('Examples', '100%', '410px')}}
+
+## Specifications
+
+{{Specifications}}
+
+## Browser compatibility
+
+{{Compat}}
+
+## See also
+
+- {{domxref("Document.getElementById()")}}