How to getElementByClass instead of GetElementById with JavaScript?

前端 未结 7 779
孤街浪徒
孤街浪徒 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:55

    document.getElementsByClassName('CLASSNAME')[0].style.display = 'none';
    

    Acyually by using getElementsByClassName, it returns an array of multiple classes. Because same class name could be used in more than one instance inside same HTML page. We use array element id to target the class we need, in my case, it's first instance of the given class name.So I've used [0]

提交回复
热议问题