'getElementById' on HTMLelement

Solution 1:

Use a new DOMParser():

// in real it's a fetch with response text:
const HTML =  `<div id="">I dont need this</div>
               <div id="test"> I want this</div>`;
const EL = new DOMParser()
            .parseFromString(HTML, "text/html")

console.log(EL.getElementById('test'));

Solution 2:

The trick here is to create a new DOM that you can add the content to instead of creating a second HTML element belonging to your existing document.

var parser = new DOMParser();
var htmlDoc = parser.parseFromString('<div id="parent"></div>', 'text/html');

const html = `<div id="">I dont need this</div>
               <div id="test"> I want this</div>`;
const el = htmlDoc.getElementById('parent');
el.innerHTML = html;
console.log(el);
// This is not working, but I want to do this
console.log(htmlDoc.getElementById('test'));

Alternatively, you can create an element belonging to the existing document and search it with querySelector (which can be called on an element) instead of document.

const html = `<div id="">I dont need this</div>
               <div id="test"> I want this</div>`;
const el = document.createElement('div');
el.innerHTML = html;
console.log(el);
// This is not working, but I want to do this
console.log(el.querySelector('#test'));