tags:

views:

80

answers:

3

Hello friends,

I get this javascript error message

Error: a.getAttribute("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.

+2  A: 

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.

Pascal MARTIN
thanks .. it works.
+1  A: 

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.

David Dorward
+1  A: 

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")
David Hedlund