RegExp.escape = function(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}

var allLabels = inDocument.getElementsByTagName("label");
var regExp = new RegExp('^\\W*' + RegExp.escape(locator) + '(\\b|$)', 'i');

var candidateLabels = $A(allLabels).select(function(candidateLabel){
  var labelText = getText(candidateLabel).strip();
  return (labelText.search(regExp) >= 0);
});

if (candidateLabels.length == 0) {
  return null;      
}

//reverse length sort
candidateLabels = candidateLabels.sortBy(function(s) {
  return s.length * -1;
});

var locatedLabel = candidateLabels.first();
var labelFor = locatedLabel.getAttribute('for');

if ((labelFor == null) && (locatedLabel.hasChildNodes())) {
  // TODO: should find the first form field, not just any node
  return locatedLabel.firstChild;
}

return selenium.browserbot.locationStrategies['id'].call(this, labelFor, inDocument, inWindow);

// Credit to: http://simonwillison.net/2006/Jan/20/escape/
RegExp.escape = function(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}

var allLabels = inDocument.getElementsByTagName("label");
var regExp = new RegExp('^\\W*' + RegExp.escape(locator) + '(\\b|$)', 'i');

var candidateLabels = $A(allLabels).select(function(candidateLabel){
  var labelText = getText(candidateLabel).strip();
  return (labelText.search(regExp) >= 0);
});

if (candidateLabels.length == 0) {
  return null;      
}

//reverse length sort
candidateLabels = candidateLabels.sortBy(function(s) {
  return s.length * -1;
});

var locatedLabel = candidateLabels.first();
var labelFor = locatedLabel.getAttribute('for');

if ((labelFor == null) && (locatedLabel.hasChildNodes())) {
  return locatedLabel.getElementsByTagName('button')[0]
    || locatedLabel.getElementsByTagName('input')[0]
    || locatedLabel.getElementsByTagName('textarea')[0]
    || locatedLabel.getElementsByTagName('select')[0];
}

return selenium.browserbot.locationStrategies['id'].call(this, labelFor, inDocument, inWindow);

Fix "element.getAttribute is not a function" Selenium errors when filling in fields
Fix "element.getAttribute is not a function" Selenium errors when filling in fields

The root cause was the locator strategy was naively returning an element that was not a form field, causing Selenium's internals to blow up
