开发者

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

开发者 https://www.devze.com 2023-01-19 02:55 出处:网络
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[a

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

精彩评论

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