HTMLCollection: namedItem() method
The namedItem()
method of the HTMLCollection
interface returns the first Element
in the collection whose id
or name
attribute match the specified name, or null
if no element matches.
In JavaScript, using the array bracket syntax with a String
, like collection["value"]
is equivalent to collection.namedItem("value")
.
Syntax
Parameters
key
is a string representing the value of the id
or name
attribute of the element we are looking for.
Return value
Example
HTML
<div id="personal">
<span name="title">Dr.</span>
<span name="firstname">Carina</span>
<span name="lastname">Anand</span>
<span id="degree">(MD)</span>
</div>
JavaScript
const container = document.getElementById("personal");
const titleSpan = container.children.namedItem("title");
const firstnameSpan = container.children["firstname"];
const lastnameSpan = container.children.lastname;
const degreeSpan = container.children.namedItem("degree");
const output = document.createElement("div");
output.textContent = `Result: ${titleSpan.textContent}${firstnameSpan.textContent}${lastnameSpan.textContent}${degreeSpan.textContent}`;
container.insertAdjacentElement("afterend", output);
Specification
Browser compatibility
|
Desktop |
Mobile |
|
Chrome |
Edge |
Firefox |
Internet Explorer |
Opera |
Safari |
WebView Android |
Chrome Android |
Firefox for Android |
Opera Android |
Safari on IOS |
Samsung Internet |
namedItem |
1 |
12 |
1 |
8 |
≤12.1 |
1 |
4.4 |
18 |
4 |
≤12.1 |
1 |
1.0 |