I have a simple site. It does a fetch to another html page. That's working and I have some response. Now I want a part of the page and select the id 'test' from the HTML. Now I created a HTMLelement, but how can I select a part of it?
How can I do this without adding all the HTML to the dom.
<html>
<body>
<script>
// 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 = document.createElement('html')
EL.innerHTML = HTML;
console.log(EL);
// This is not working, but I want to do this
console.log(document.getElementById('test'));
</script>
</body>
</html>
CodePudding user response:
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'));
CodePudding user response:
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'));