views:

35

answers:

2

hi guys,

I am trying to find the list of elements that matches the specified id format.
like I want to select all the tags with classname "required" or select all the tags with id like myObj[any char] eg. myObj1, myObj2, myObj3, myObja etc

+2  A: 

You'll have to do it by iterating over all the elements in the DOM:

var allElements = document.getElementsByTagName('*');
for (var i = 0; i < allElements.length; ++i) {
  var element = allElements[i];
  if (/\brequired\b/.test(element.className) || /^myObj?/.test(element.id)) {
    // whatever
  }
}

Some smarty person will probably be able to explain how to do this with path selectors; I'm not very familiar with that and also it won't work on old IE versions anyway.

Pointy
thnx pointy your idea helped me.
KoolKabin
+1  A: 

Get elements by class name:

document.getElementsByClassName('foo bar baz');

See Pointy's answer for selecting by ID prefix.

That said, you're really better off using a library to do all that nasty stuff for you.

Matt Ball
It's true that a framework is a good idea here - at worst, it'll have to do the same sort of iteration over the whole DOM, but a good framework will be able to use more sophisticated techniques in browsers that support them.
Pointy
@Pointy - **yes.** For the OP - for example, many libraries (like jQuery, YUI, etc.) will use native, non-standard browser selector API methods when available that are _way_ more efficient, such as Gecko's [querySelectorAll](https://developer.mozilla.org/En/DOM/Element.querySelectorAll).
Matt Ball