Now that is all nice but we also had the thing that I wanted to get this template out of this DOM,
now how does that work?
First of all, let me say that having a template in our normal HTML file is of course fine, as you see, it
works
but if we want to create a fully reusable web component, it would be nice to define the template in the
Javascript file too so that in the end, we just have to dump this Javascript file into any project, any
web project and we can start using our own component
and for this I'll go back to the tooltip.js file and I will define a template in there which is really
easy. Instead of appending our template content, so I can get rid of these two files here, I will access
my shadow root
and there we can set the innerHTML code, innerHTML is a default property you can set on your
HTML elements, on the built-in ones too and there you can write any HTML code you want.
So now we can grab this content we had in the template and remove the template thereafter and add this
here, like this. If you save that and you then reload this page, you have the same as before, the same behavior
as before but now, you have your template as part of your Javascript file.
Now I know that it can look strange to start writing HTML inside of your Javascript file,
keep in mind that this in the end is just a normal string and it can look strange but it is a nice way
of creating a reusable HTML element.
Now we can also use a next gen Javascript feature called template literals where we use back ticks instead
of single quotation marks,
so this is not a single quotation mark, this is a back tick, opening and closing and this will still create
a string but now we can write a multiline string here so that we can format this in a nicer way. If we now
save this,
you will see it still works as before.
So it's just a bit strange to get used to that, in some IDEs, you get really great auto completion support here
though, mine doesn't pick it up here but still I will go with this approach because whilst it is strange
to look at, we now have all the logic in the Javascript file, making this a really simple reusable web
component.
Now one important thing, you might wonder how can I set the HTML content here inside my constructor?
The reason is simple, innerHTML is just a property of our element here, of our object and this
is just setting up some HTML code that will be rendered to to DOM once this element is mounted
to the DOM.
So unlike append child, this does not try to access the DOM at this point, it just prepares some content
for the DOM once it later is available and the browser will take care about rendering this when it is
able to.