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")
.
<div id="personal">
<span name="title">Dr.</span>
<span name="firstname">Carina</span>
<span name="lastname">Anand</span>
<span id="degree">(MD)</span>
</div>
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);