Home > database >  Unable to access elements from a file that is included by javascript
Unable to access elements from a file that is included by javascript

Time:03-02

I created a single navbar.html and included it in all the pages of my website.j The css works fine but the javascript is unable to select elements from that navbar.

navbar.html:

<nav >
    <h1>
        This is a navbar
    </h1>
</nav>

index.html where it is replaced with a placeholder:

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
   <div ></div>
    <script src="app.js"></script>
</body>
</html>

app.js that is replacing the navbar and implementing a test function:

$(function(){
    $(".nav-placeholder").load("nav.html");
  });

document.querySelector('.navbar').addEventListener('click', function(){
    alert('clicked');
})

CodePudding user response:

You're trying to bind your event listener before the load function had inserted the data into the DOM.

Either use event delegation or move the work of binding the event listener into a callback function you pass as the second argument to the load method.

  • Related