开发者

How to avoid javascript "rel" is null error? please have a look a on code provided

I get this javascript error message

Error: a.getAttri开发者_运维知识库bute("rel") is null

on these lines of code

  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;

any ideas how do I sort it out?

Thanks.


Before using a.getAttribute("rel") like you are doing :

if(a.getAttribute("rel").indexOf("style") != -1 && 
    a.getAttribute("title") && 
    !a.disabled) {
    return a.getAttribute("title");
}

You should test if it's not null (or not "falsy") :

if(a.getAttribute("rel") &&
    a.getAttribute("rel").indexOf("style") != -1 && 
    a.getAttribute("title") && 
    !a.disabled) {
    return a.getAttribute("title");
}

With the first portion of condition I added at the beginning of the if expression, the second (and the ones after) portion of the condition will be evaluated only if a.getAttribute("rel") is truthy -- i.e. the won't be evaluated when a.getAttribute("rel") is null.


Check that rel is defined before you try to treat it as a string.

var rel = a.getAttribute("rel") ;
if(rel && rel.indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) {
    return a.getAttribute("title");
}

Since you only care about it if it has 'style' in it, we don't need to be explicit about checking that it is defined, and can just test that it is truthy.


Your loop is hitting an a that doesn't have rel specified (i'm guessing this would apply to most of them).

if(!a.getAttribute('rel')) continue;
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜