YouTip LogoYouTip

Met Htmlcollection Nameditem

## HTMLCollection namedItem() Method The `namedItem()` method returns the element with the specified `id` or `name` attribute from an `HTMLCollection` object. If the collection contains more than one element with the specified name or ID, it returns the first matching element. If no matching element is found, it returns `null`. --- ## Syntax ```javascript htmlCollection.namedItem(name) ``` ### Alternative Shorthand Syntax In JavaScript, you can also access named items using bracket notation or property notation, which is more common in modern development: ```javascript htmlCollection // or htmlCollection.name ``` ### Parameters | Parameter | Type | Description | | :--- | :--- | :--- | | `name` | *String* | **Required.** The value of the `id` or `name` attribute of the element you want to retrieve. | ### Return Value * **Element Object**: Returns the first element matching the specified `id` or `name`. * **null**: Returns `null` if no matching element is found. --- ## Browser Support The `namedItem()` method is fully supported across all modern browsers: | Method | Chrome | Edge | Firefox | Safari | Opera | | :--- | :--- | :--- | :--- | :--- | :--- | | `namedItem()` | Yes | Yes | Yes | Yes | Yes | --- ## Code Examples ### Example 1: Using `namedItem()` to Retrieve an Element by ID This example demonstrates how to retrieve a specific `

` element from an HTMLCollection using its ID. ```html HTMLCollection namedItem() Example

This is the first paragraph.

This is the target paragraph with ID "myElement".

This is the third paragraph.

``` ### Example 2: Using Bracket Notation Shorthand You can achieve the exact same result using the bracket notation shorthand, which is cleaner and widely used: ```javascript function myFunction() { // Retrieve the element using bracket notation var x = document.getElementsByTagName("p"); if (x !== null) { alert(x.innerHTML); } } ``` --- ## Considerations and Best Practices * **ID vs. Name**: The `namedItem()` method searches for elements matching either the `id` attribute or the `name` attribute. For form controls (like ``, `