getElementById() wildcard

Not in native JavaScript. You have various options:

1) Put a class and use getElementsByClassName but it doesn’t work in every browser.

2) Make your own function. Something like:

function getElementsStartsWithId( id ) {
  var children = document.body.getElementsByTagName('*');
  var elements = [], child;
  for (var i = 0, length = children.length; i < length; i++) {
    child = children[i];
    if (child.id.substr(0, id.length) == id)
      elements.push(child);
  }
  return elements;
}

3) Use a library or a CSS selector. Like jQuery 😉

Leave a Comment