How to get element in template html?

Viewed 1220

I am developing an Electron app, in which the index.html imports a search.html:

<link rel="import" href="search.html">

And inside the search.html, I create a button whose id is searchBtn.

Then, in the redenerer.js, I try to get the searchBtn:

var link = document.querySelector('link[rel="import"][href="search.html"]');
var content = link.import.querySelector('template');
console.log(content);
var searchBtn = content.querySelector('#searchBtn');  
console.log(searchBtn);

The output of the first log is expected, but the second log for searchBtn is always null.

Is there any wrong with my code? If so, how to obtain the element in template html correctly?

The output is following:

enter image description here

I notice that there is a document-fragment inside the template.

2 Answers

Run the querySelector function on the templates content property.

var link = document.querySelector('link[rel="import"][href="search.html"]');
var templateContent = link.import.querySelector('template');
console.log(templateContent);
var searchBtn = templateContent.content.querySelector('#searchBtn');  
console.log(searchBtn);

More about document fragment.

More about template.

Working sandbox;

Try like this :

// parse you HTML first
var html = link.import.querySelector('template');
var parser = new DOMParser();
var doc = parser.parseFromString(html.content, "application/xml");

//later
var searchBtn = doc.querySelector('#searchBtn');  
console.log(searchBtn);
Related