简体   繁体   中英

is null or not an object in IE8/7 by using javascript

the JavaScript is like this:

    <script type="text/javascript">
var links = document.getElementById("practice_nav_var_color");
var a = links.getElementsByTagName("a");
var thisLocationHref = window.location.href;
for(var i=0;i<a.length;i++){ 

  var tempLink = a[i];      

  if(thisLocationHref === tempLink.href)
  {
      tempLink.style.backgroundColor="#7387a2";
  }
  else
  {
      tempLink.style.backgroundColor="#8d8679";
  }
}

In IE8, the error message says "links" is null or not an object.
So my first guess is IE doesn't like document.getElementById...

I have searched online, it seems like it has conditional statements previous to the div, which I am not sure what that mean.

Any help is welcome. Thank you for your time!

try this

var links = document.getElementById("practice_nav_var_color");
if(links) {
    var a = links.getElementsByTagName("a");
    var thisLocationHref = window.location.href;
    for(var i=0;i<a.length;i++){ 

          var tempLink = a[i];      

        if(thisLocationHref === tempLink.href)
        {
            tempLink.style.backgroundColor="#7387a2";
        }
        else
        {
            tempLink.style.backgroundColor="#8d8679";
        }
    }
}

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