Hide show in JavaScript using classes instead of ids -
i have seen previous questions trying use classes instead of ids hide show in javascript. however, haven't found definitive answers. need use class because have faq section inputting questions , hide / showing answers. here's code using ids:
<script type="text/javascript"> function toggle() { var ele = document.getelementbyid("toggletext"); var text = document.getelementbyid("displaytext"); if(ele.style.display == "block") { ele.style.display = "none"; text.innerhtml = text() + " show"; } else { ele.style.display = "block"; text.innerhtml = text() + " hide"; } } </script>
how change javascript use classes? tried changing getelementbyid getelementbyclassname, don't know why didn't work.
you missing conceptual difference between classes , ids. classes not unique, not able retrieve single element when querying class. can surely list single element, still list because can possibly have more 1 element same class. on other hand, ids unique, , why can select direct element using method id.
the correct javascript method retrieving objects class getelementsbyclassname
(note s
return list of elements, , not single result expected).
you have parse returned list element(s) want.
just illustrate, can toggle display
attribute of first returned element doing:
var displayedtexts = document.getelementsbyclassname("displaytext"); displayedtexts[0].style.display = "none";
you can see js fiddle simple example here.
Comments
Post a Comment