Grant Curell
Grant Curell

Reputation: 1783

htmlcollection - how do you get elements by id?

I have the following code however it does not work:

let dummyDOM = document.createElement( 'html' );
dummyDOM.innerHTML = text;
const html = dummyDOM.getElementById("someID");

I receive: Uncaught (in promise) TypeError: dummyDOM.getElementById is not a function

I know how to get elements by class name but I have not seen a way to get elements by ID. Is this possible with htmlcollection?

Upvotes: 0

Views: 2322

Answers (2)

tenshi
tenshi

Reputation: 26374

Under usage notes from MDN:

Unlike some other element-lookup methods such as Document.querySelector() and 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.

That means a regular element doesn't have this method. However, regular elements still have a querySelector method, that gets the first element found that matches a CSS selector.

const html = dummyDOM.querySelector("#someID");

Or, if you are planning to add dummyDOM to the page, you could just use the original getElementById:

const html = document.getElementById("someID");

But what you really need is a proper Document, which you can do with createDocument:

let dummyDOM = document.implementation.createDocument();

Upvotes: 3

ethry
ethry

Reputation: 805

If you want to get an element by its ID, you can use the getElementById() method that you are already using.

For example:

function changeCol(c = "cyan") {
  document.getElementById("id1").style.backgroundColor = c;
}
p {
  background-color: lime;
}
<p id="id1">ID 1</p>
<p>Not ID 1</p>

<button onclick="changeCol('magenta');">Change background</button>

You can learn more about getElementById() at:

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

https://devdocs.io/dom/document/getelementbyid

Upvotes: 0

Related Questions