简体   繁体   中英

Adding css class using javascript to header that is implemented using javascript

I am developing a website with many html files and just recently i started using seperated header and footer html files in order to save time by implementing them using javascript to my pages. The problem is now all the header and footer looks the same, while before using this handy technique i had the pages highlighted depending on the page you were on(this was done by manually adding class to different <a> tags depending on what the page(html file) it is), but now i can't find a way to target a specific <a> that would be targeted only on specific html to change it's css. The code looks something like this: HTML home.html:

  <div id="header"></div>

HTML header.html:

  <ul>
  <li id="LI_56">
              <a href="pages/home.html" id="A_57">Home</a>
  </li> 
  </ul> 

Javascript looks like this:

$(function(){
  $("#header").load("header.html"); 
  $("#footer").load("footer.html"); 
});

css looks like this:

.home{
background-color:red;
}

and what I tried to do is:

          <script>
          $( document ).ready(function() {
          document.getElementById('A_57').className = 'home';
          }); 
          </script>

But i get error:"TypeError: document.getElementById(...) is null" . When the header is already in my home.html and not implemented by javascript everything works fine, but that's no an option. Hoping anyone knows a solution. Using diffrent css files for each html is also clearly not an option - it should be as straight forward and developer friendly(smart & lazy) as possible! :) Thanks in advance!

This is because the element doesn't yet exist. Add the class after the html has been loaded.

$(function(){
    $("#header").load("header.html", function() {
        var $homeLink = $('#header').find('a').filter(function() {
            return $.trim($(this).text()) === 'Home'
        });

        $homeLink.addClass('home');
    }); 
    $("#footer").load("footer.html"); 
});

Set the class name in a "complete" callback, this callback is executed after post-processing and HTML insertion has been performed:

$(function(){
  $("#header").load("header.html", function() {
      document.getElementById('A_57').className = 'home';
  });
  $("#footer").load("footer.html"); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM