Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
So far, we've looked at picking elements by ID and tag name. So, you're probably thinking that you can also pick elements by class name, and you would be right, sort of. The getElementsByClassName function is a bit of a new addition. Of course, it does that you select that elements with a specific class, but because it is a newer selector it is incompatible with older browsers. Whenever you have a question about whether a browser has support for a method, you should check out a couple of web pages. This one right here called caniuse.com is a really good resource. So, if you scroll down you can see that this method has support in pretty much every modern browser but not older versions of IE. Another page you should check out is the W3C.ompatibilty.
If you scroll down on this page see you can get to the same information on the get element by class name method. Now, I'm using a pretty modern browser here this is a late version of Chrome so you shouldn't have a problem with this method. So, I'm going to go to my website I'll click on the Artists section this time. So, this page just has a list of artists right here. And I'm going to break into the developer tools by hitting Cmd option I that would Ctrl+Alt+I on the PC and then hitting the Escape key. And then I can type in document. (SOUND) getElements, remember it's plural, ByClassName. Then, I can type in the class name that I'm looking for. So if you don't know the class name, you can hit this magnifying glass. And just click on any one of these images, and it gives you the whole path to that element.
So, this element has a class of artists, so I'll type that in. And it returns every single artist on this page. Now if you have to many items match in a class, say that you had two separate lists of artists. You can get more specific by first finding the element with the ID. So you could do something like document, get element by ID, and then type it in first the ID. So, we know that looking at the breadcrumbs we can see that this has an ID of artist list, and then we can do get elements by class name.
So, this takes us to the same place but if you had multiple lists on the same page with the same class, this might be a better target. So as I mentioned earlier, this function is not supported on IE or earlier. Because of this a lot of people have written their own implementation usually called a polyfill of the get elements by class name method. That's so that they can support older browsers. If you want to check some of those out you may want to go to this URL right here this page is put together by John Resig creator of jQuery.
Get unlimited access to all courses for just $25/month.Become a member