How to getElementByClass instead of GetElementById with JavaScript?

前端 未结 7 705
孤街浪徒
孤街浪徒 2020-11-22 09:33

I\'m trying to toggle the visibility of certain DIV elements on a website depending on the class of each DIV. I\'m using a basic JavaScript snippet to toggle them. The probl

7条回答
  •  长发绾君心
    2020-11-22 09:49

    Modern browsers have support for document.getElementsByClassName. You can see the full breakdown of which vendors provide this functionality at caniuse. If you're looking to extend support into older browsers, you may want to consider a selector engine like that found in jQuery or a polyfill.

    Older Answer

    You'll want to check into jQuery, which will allow the following:

    $(".classname").hide(); // hides everything with class 'classname'
    

    Google offers a hosted jQuery source-file, so you can reference it and be up-and-running in moments. Include the following in your page:

    
    
    

提交回复
热议问题