How I select class in js?

1Html=> <div class="main">hello</div> <button onclick="myfunc()">click</button> ______________________________________ 2CSS :=> .Main{display:none;} ______________________________________ 3JavaScript=> function myfunc() { Var trick = document.getElements ByClassName('main'); Trick.style.display='block' ; } ______________________________________ 1.This program why not work? 2.And also cay you send correct syntax of selecting class?

4/7/2019 12:07:47 PM


3 Answers

New Answer


trick is an array of the elements It holds all the same class elements. var trick = document.getElementsByClassName('main'); // return an array // so to set the first .main element trick[0].style.display='block' ; // to set the second .main element trick[1].style.display='block' ; // to set the 3rd .main element, if available and so on trick[2].style.display='block' ;




You can select class by these two methods 1:- Var trick= document.getElementsByClassName("main"); 2:- var trick= document.querySelector(".main"); Remember: use dot(.) in query selectors and # in to select id's in querySelector if id= "main" Then Var trick = document.querySelector("#main");