The Context
To make the explanation of my issue easier, I have created a small example:
Let’s say we have this simple website (index.html
):
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<body>
<script id="navigation" src="nav.js"></script>
<p>Amazing website content</p>
<script src="something.js"></script>
</body>
</html>
Let’s say the nav.js
script imports our navigation bar from a nav.html
into our index.html
, so the script would look something like this:
fetch('nav.html')
.then(res => res.text())
.then(text => {
let oldE = document.querySelector("script#navigation");
let newE = document.createElement("div");
newE.innerHTML = text;
oldE.parentNode.replaceChild(newE,oldE);
})
and for simplicity sake our “navigation bar” (nav.html
) looks like this:
<ul class="class-nav">
<li><a href="#">Home</a></li>
<li><a href="#">News</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">About</a></li>
</ul>
Finally, we have something.js
which is a javascript that uses jQuery to do some stuff, for now, we just want to be able to print out elements with the class name class-nav
:
jQuery(document).ready(function($) {
"use strict";
var magic = function() {
$('.class-nav').each(function() {
console.log(this);
});
};
magic();
});
The Issue
If I hardcoded my navigation bar (nav.html
) to the webpage (index.html
), the magic()
function in something.js
(that uses jQuery) works and is able to print out the navigation bar class-nav
.
However, if we have it in the current setup, where we have our navigation bar added to the webpage from a separate nav.html
file, the magic()
function isn’t able to find class-nav
.
Why? And how can I modify something.js
to be able to retrieve class-nav
using jQuery?