开发者

How do I select class within a class or a tag using Javascript getElementsByClass() function?

开发者 https://www.devze.com 2023-02-02 23:05 出处:网络
In jQuery it would simply be $(\"a.class\").randommethod(); or $(\".class1 .class2\").randommethod(); How do I achieve the same effect using pure Javascript? (I\'m editing a open-source softwar

In jQuery it would simply be

$("a.class").randommethod();

or

$(".class1 .class2").randommethod();

How do I achieve the same effect using pure Javascript? (I'm editing a open-source software for personal use and it does开发者_如何学编程n't use jQuery)


You can't do it using getElementsByClassName. You would need to use something more like querySelectorAll, which accepts CSS style selectors.

var result = document.querySelectorAll('.class1 .class2');

You should note that neither method has full cross-browser support. That's why people use javascript libraries. If you don't need to support older browsers, then querySelectorAll is a good choice.

Another option is to use the Sizzle selector engine that jQuery uses.


You'll need to write your own selector engine, or use an established one such as sizzle (http://sizzlejs.com/), which is used by jQuery.

0

精彩评论

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

关注公众号