Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add DocumentFragment.getElementById() #24449

Merged
merged 17 commits into from
Mar 29, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions files/en-us/web/api/document/getelementbyid/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, or a fragment of a document. If it is not the case, this method returns the first occurrence found.
teoli2003 marked this conversation as resolved.
Show resolved Hide resolved

## 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 case-sensitive string which is unique within the document; only one element should have any given ID.
teoli2003 marked this conversation as resolved.
Show resolved Hide resolved

### Return value

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -100,15 +102,15 @@ 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 `<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 {{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()`:
teoli2003 marked this conversation as resolved.
Show resolved Hide resolved

```js
const element = document.createElement('div');
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 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`.
teoli2003 marked this conversation as resolved.
Show resolved Hide resolved

## Specifications

Expand Down
159 changes: 159 additions & 0 deletions files/en-us/web/api/documentfragment/getelementbyid/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
---
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, or a fragment of a document. If it is not the case, this method returns the first occurrence found.
teoli2003 marked this conversation as resolved.
Show resolved Hide resolved

## 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.
teoli2003 marked this conversation as resolved.
Show resolved Hide resolved

## Examples

### HTML
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's good practice to have a descriptive H3 for the whole example, and to make the "HTML" etc headings H4 headings under that.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These are kind of picky comments, because this example does work fine and illustrate what it wants to. So please feel free to ignore, or use whatever parts you want to.

The behavior of this example isn't very easy to understand, and there is a lot of code to read - almost 100 lines.

I think with examples like this where we are basically showing state changes, it's better to make them more interactive, so the reader can see the current state and move on to the next state. Otherwise by the time the page is loaded, the whole story is told and I have to piece together what happened.

So maybe consider:

  • 3 buttons:
    • one labeled something like "Find elements" that looks for find Apple and Durian in the document fragment and document, and logs the results
    • one labeled "Add fragment to document" that adds the fragment
    • one labeled "Reset" that reloads the iframe, so the reader can try again

That way it's easier to understand the initial state and how the state changes when we add the fragment.

It's also I think preferable to include explanatory text in prose, outside the example, rather than inside (for example, it means people who have dark theme for readability will get the benefit of that.

Finally, the code that logs the results is quite verbose:

output.append(document.createElement("br"));
output.append(
  document.createTextNode(
    `Found Apple in the fragment? ${
      fragment.getElementById("Apple") ? "Yes" : "No"
    }`
  )

...and this contributes to this example looking long. This is really just framework code (i.e. it's not an essential part of the example) so it is distracting. In similar cases I make the output a <pre> and just do:

output.textContent +=  `Found Apple in the fragment? ${
      fragment.getElementById("Apple") ? "Yes" : "No"
    }\n`

(e.g. https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#bubbling_example)


```html
Durian is initially the only entry of this list. The other list items have been
teoli2003 marked this conversation as resolved.
Show resolved Hide resolved
added to a fragment, subsequently added to this unordered list:
<ul>
<li id="Durian">Durian</li>
</ul>

Before appending the fragment to the document, we find Durian in the document
and Apple in the document fragment:<br />
<output></output>
<br /><br />
After appending the fragment to the document, we find both in the document:<br />
<output></output>
```

### JavaScript

```js
// Obtain the unordered list in the document
const ul = document.querySelector("ul");

// Create the document fragment
const fruits = ["Apple", "Orange", "Banana", "Melon"];

const fragment = new DocumentFragment();

for (const fruit of fruits) {
const li = document.createElement("li");
li.textContent = fruit;
li.id = fruit;
fragment.append(li);
}

// Perform the searches
let output = document.querySelectorAll("output")[0];
output.append(document.createElement("br"));
output.append(
document.createTextNode(
`Found Apple in the fragment? ${
fragment.getElementById("Apple") ? "Yes" : "No"
}`
)
);
output.append(document.createElement("br"));
output.append(
document.createTextNode(
`Found Apple in the document? ${
document.getElementById("Apple") ? "Yes" : "No"
}`
)
);
output.append(document.createElement("br"));
output.append(
document.createTextNode(
`Found Durian in the fragment? ${
fragment.getElementById("Durian") ? "Yes" : "No"
}`
)
);
output.append(document.createElement("br"));
output.append(
document.createTextNode(
`Found Durian in the document? ${
document.getElementById("Durian") ? "Yes" : "No"
}`
)
);

// Insert the fragment inside the document's unordered list
ul.append(fragment);

// Perform the searches
output = document.querySelectorAll("output")[1];
output.append(document.createElement("br"));
output.append(
document.createTextNode(
`Found Apple in the fragment? ${
fragment.getElementById("Apple") ? "Yes" : "No"
}`
)
);
output.append(document.createElement("br"));
output.append(
document.createTextNode(
`Found Apple in the document? ${
document.getElementById("Apple") ? "Yes" : "No"
}`
)
);
output.append(document.createElement("br"));
output.append(
document.createTextNode(
`Found Durian in the fragment? ${
fragment.getElementById("Durian") ? "Yes" : "No"
}`
)
);
output.append(document.createElement("br"));
output.append(
document.createTextNode(
`Found Durian in the document? ${
document.getElementById("Durian") ? "Yes" : "No"
}`
)
);
```

### Result

{{EmbedLiveSample('Examples', '', '500')}}

## Specifications

{{Specifications}}

## Browser compatibility

{{Compat}}

## See also

- {{domxref("Document.getElementById()")}}
- {{domxref("DocumentFragment.querySelector()")}} and {{domxref("DocumentFragment.querySelectorAll()")}}for selectors via queries like `'div.myclass'`
teoli2003 marked this conversation as resolved.
Show resolved Hide resolved