3

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.

3
  • The log shows that the content is the template, in which there is a document-fragment. Commented Nov 12, 2018 at 14:38
  • 1
    Can you set up a demo page? maybe on codepen? Commented Nov 12, 2018 at 14:42
  • Might be helpful html5rocks.com/en/tutorials/webcomponents/imports Commented Nov 12, 2018 at 15:16

2 Answers 2

5

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;

Sign up to request clarification or add additional context in comments.

2 Comments

It works now. It seems that the we should access the document fragment via content property.
I now have problems with the event binding: how-to-bind-the-event-in-html-template
0

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);

1 Comment

the doc is empty.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.