Set The Color Of A Link That Is Loaded From The JQuery '.load()' Method

- 1 answer

In my index.html file I have the following code:

<div id="navbar"></div>

<script type="text/javascript">
    $(document).ready(function() {
        $('head').append('<link rel="stylesheet" type="text/css" target="_blank" rel="nofollow noreferrer" href="stylesheets/navigation.css">');

and the navigationbar.html file is:

            <li><a id="nav-page-1" target="_blank" rel="nofollow noreferrer" href="page1.html">Page 1</a></li>
            <li><a id="nav-page-2" target="_blank" rel="nofollow noreferrer" href="page2.html">Page 2</a></li>

The markup and stylesheets load and show correctly, but what I wanted to do was copy and paste the jQuery code in every page. However, the difference would be that on page one the color or "Page 1" should be different than the other links on the bar, and on page two the color of "Page 2" should be a different color, etc. How could I achieve this with the above code?

I tried:

document.getElementById("nav-page-1").color = "#ff0000";

But that didn't work. Any suggestions?



You need to select the element in a callback after the HTML has been added.

$("#navbar").load("scripts/navigationbar.html", function () {
  document.getElementById("nav-page-1").style.color = "#ff0000";

Based on the code you provided, you were probably trying to select the element before it existed. The .load() method is asynchronous, so that logic should be added in a callback so that it is fired when the event completes. As a side note, you also need to access the color property on the style object (i.e., rather than element.color).