I had 2 nice answers on my question and they helped me to find a more suitable solution for my specific problem I'm sharing here.
Again what I tried to achieve was to querySelector
an element defined in an html import from the main document (i.e. index.html
).
If we write something like
<div id="thediv">
...
</div>
at the root of an html import, the element won't be included in the body of the main document (I think each document has its own namespace or something like that).
@guest271314 recommended to use the import
property of a link
element to access the content of the fetched resource but see my comment on the same post. I think this is not really neat when you deal with documents that imports other documents that imports others...
@MaxBilbow recommended the same method providing a link and an example chunk using template
. Again this is not really nice when you deal with relational imports. But the link gave me the solution.
In my imported document, I write an additional script :
div.html
<div id="thediv">
...
</div>
<script>
document.body.prepend(
document.currentScript.ownerDocument.querySelector('#thediv'));
</script>
Now when the html import is fetched the script will get executed and prepend the html chunk into the body
of the main document.
index.html
<link rel="import" href="div.html">
<script>
// now I can querySelector('#thediv')
</script>
This is just an example and it is a dummy one, but I think I will mostly use that technique for templates, templates are hidden and it's ok to prepend them to the main document.
If you think that method could have flaws, please comment.