Reusable html with Javascript

I am trying to reuse a piece of html code that i need for many pages.

There is a folder called bar, and inside :


There is the main page index.html, in another folder where i include this whole 3 files (bar.css+js+html).

I load the bar.html into index.html with :


It works and I get to see on index.html this bar with its css styles.

But, the Javascript have problem, where inside the bar.js i get an error on this line :

var element = document.getElementById('bar');

it says it can't find this element (null) but it is inside bar.html ( which included in index.html as showed here).

How to do this properly so it will identify this element ?