How do I select class within a class or a tag using Javascript getElementsByClass() function?
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.
精彩评论