0

I have a template file that I get from the server using ajax. The file is something like that

<!DOCTYPE HTML>
<html>
<body>
<script id="temp_1" type="x-tmpl-mustache">
    Hello {{ name }}!
</script>

<script id="temp_2" type="x-tmpl-mustache">
    Hello {{ name }}!
</script>
</body>
</html>

How can I access the innerHTML of temp_1 and temp_2 without inserting the file into the page? Basically, this is what I'm trying to achieve.

var templates;
$.get( "templates.html", function( data ) {
  templates = data;
});

// Access the dom element like this
// templates.document.querySelector('#temp_1').innerHTML > Hello {{ name }}!

I've said it in the comment but gonna say it again

I've fixed the problem with using DOMParser which you can see here. @23528 marked my question as duplication and linked to another question which has nothing to do with my question. So if you are having the same problem, use DOMParser.

Monke
  • 55
  • 9
  • `var templates; $.get( "templates.html", function( data ) { templates = data; }) .done(function(data) { console.log(data.documentElement.querySelector('#temp_1').innerHTML) });` – Ivan Jun 11 '18 at 17:38
  • @Ivan I am getting "Cannot read property 'querySelector' of undefined..." error with your code even though data is the HTML code in string form and id's are matching. – Monke Jun 11 '18 at 17:51
  • I've fixed the problem with using DOMParser which you can see here > https://developer.mozilla.org/en-US/docs/Web/API/DOMParser Also, @23528 marked my question as duplication and linked to another question which has nothing to do with my question. – Monke Jun 11 '18 at 17:58
  • It does have a something to do with your question. Because you're trying to select the element from `templates` while `$.get()` is an asynchronous function. Therefore you need to wait for the response to come back before looking to get the item. I recommend you to [read more on asynchronous calls in JavaScript](https://stackoverflow.com/a/14220323/6331369). It will help with your project. – Ivan Jun 11 '18 at 18:11

0 Answers0