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?
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();