开发者

how to select elements with specific id without using javascript frameworks?

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 "requi开发者_开发问答red" or select all the tags with id like myObj[any char] eg. myObj1, myObj2, myObj3, myObja etc


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜