How to Hide by Class in JavaScript

JavaScript is a programming language used to allowed websites to interact with the user. It allows pages to display pop-ups, asynchronously send requests to the server and create drop-down menus, to name a few examples. Despite JavaScript's functions for finding elements by ID and name, it does not have a function for finding elements by class. You can, however, hide elements by class by looping over all elements, checking if their class matches the searched-for class and, if so, hiding the element.

Instructions

    • 1

      Create a new file and save it with a ".html" file extension. Open the file with a text editor, such as Notepad.

    • 2

      Write a segment of HTML code that creates a button with an "onClick" attribute of "hide()." This will call the JavaScript function "hide" when the button is clicked. Here is the code:

      <button onClick="hide()">Hide</button>

    • 3

      Write a segment of HTML code that creates a number of HTML elements with the class "hideable." These elements will be hidden when the button from the previous step is clicked. Here is an example:

      <div class="hideable">This is a hideable div</div>

      <span class="hideable">This is a hideable span</span>

    • 4

      At the beginning of the file, write the opening and closing HTML "script" tags. These tell the browser that the code inside them is JavaScript. Here is the code:

      <script>

      </script>

    • 5

      Between the "script" tags, write a JavaScript function the hides all HTML elements with the class "hideable." First, it must get all the elements into an array by calling the "document.getElementsByTagName" function with the parameter "*" and saving the result into a new variable. Second, it must loop over each element in the array using a "for" loop. Third, it must check if the current item has the class "hideable" using the "getAttribute" method, and, if so, hide the element by setting the elements "style.display" property to "none." Here is the code:

      function hide() {

      var elements = document.getElementsByTagName("*");

      for(i = 0; i < elements.length; i++) {

      if(elements[i].getAttribute("class") == "hideable") {

      elements[i].style.display = "none";

      }}}

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured