Q: How to get element from HTML stored in variable I am running an API to retrieve email from external system. I managed to get HTML code from the returned JSON and store it in a variable. Now, I would like to run some further operations on this HTML - for example get all elements with 
[data-type="whatever"].
 It would be easy in html document:
var x = document.querySelectorAll('[data-type="whatever"]');

However the HTML document I want to work with is stored in the variable so the code I write in API does not recognise it as a document. How can I do it? Any suggestions with vanilla JS?

A: You can try something like this.


let rawDoc = '<html><head><title>Working with elements</title></head><body><div id="div1">The text above has been created dynamically.</div></body></html>'

let doc = document.createElement('html');
doc.innerHTML = rawDoc;
let div1 = doc.querySelector('#div1');
console.log(div1)



A: What if you use innerHTML? or maybe I don't fully understand the question.

A: Since you are working without a document you have 2 options.
1. Use regex to get what you need (something like /<.+>.+ data-type="whatever".+<\/.+>/gi) should do (but for an exact match you may need to make something better).


2. Insert the html in a hidden part of the dom and select what you need from it (like in Zohir answer - he provided a good example).


A: I used following code with angular to store whole html content in a variable and pass it as argument to call API. 
var htmlBody = $('<div/>').append($('#htmlBody').clone()).html();
This might work for you as i was working on sending email to pass invoice template so try this.
