0

Beginner to javascript and web development here. I have the following code. I am trying to manipulate the css for the #blog_nav element, but I am unable to get anything to render. A call to $("#blog_nav).length returns 0, which makes me believe the element does not yet exist for some reason. When I call $("#" + selected_page + "_nav").css("color": "red") in the inspect console after the page has loaded, it works fine. Any help is appreciated. Thanks

index.html

<!DOCTYPE html>

<html>

    <head>

        <title>title</title>
        <script src="js/jquery.js"> </script>
        <script type="text/javascript" src="js/site_navigation.js"></script>

    </head>

    <body>

        <aside id="right_container"></aside>

        <script type="text/javascript">
            loadSideNav("blog");
        </script>
    </body>

</html>

site_navigation.js

function loadSideNav(selected_page) {
    $("#right_container").load("components.html #side_nav");
    console.log($('#blog_nav').length); // returns 0
    $("#" + selected_page + "_nav").css("color": "red"); // doesn't work
}

components.html

<nav id="side_nav">
    <ul id="side_nav_list">
        <li><a id="blog_nav" class="nav_link" href="index.html">blog</a></li>
        <li><a id="projects_nav" class="nav_link" href="index.html">projects</a></li>
    </ul>
</nav>
echao
  • 33
  • 2
  • 1
    You need to wait for the asynchronous `.load` to complete - at the time you call `$("#" + selected_page + "_nav").css`, the network request is still pending – CertainPerformance Jan 02 '20 at 00:27
  • That was it! Used the load callback function and put my css manipulation code in there. Thank you – echao Jan 02 '20 at 01:14

0 Answers0