Using a JavaScript class rather than an ID for toggling visibility

As a complete newbie to JavaScript, I've come across similar questions but I'm lost when it comes to coding - help needed! So here's the code I have so far, and I'm hoping someone can assist me.

Currently, I have JavaScript set up to show and hide a div based on its ID, but I want to modify it to work with Class names instead. I have multiple classes that I need to toggle visibility for by clicking a button. This is for a Masterlist of Trans* characters roleplayed on Tumblr, where I want the ability to filter and display specific categories of characters with ease (like MtF trans characters only).

Here's the JS snippet I currently have. Any suggestions on how to adapt this for classes would be greatly appreciated!

<script>

    function myFunction1() {

      var x = document.getElementById('all');

    if (x.style.display === 'block') {
        x.style.display = 'none';
    } else {
        x.style.display = 'block';
    }
      document.getElementById("mtf").style.display = "block"; 
      document.getElementById("ftm").style.display = "block";
      document.getElementById("nonbinary").style.display = "block";
      document.getElementById("fluidqueer").style.display = "block";

    }
    </script>
    <script>

    // Additional functions for other class toggles...

Answer №1

Here is a helpful solution for you,

$(".filter-btn").click(function() {
  var className = $(this).attr('data-target');
  if ($("div").not("." + className).is(":visible")) {
    $("." + className).show();
    $("div").not("." + className).hide();
  } else {
    $("." + className).hide();
    $("div").not("." + className).show();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mtf">MTF</div>
<div class="mtf">MTF</div>
<div class="mtf">MTF</div>
<div class="mtf">MTF</div>

<div class="ftm">FTM</div>
<div class="ftm">FTM</div>
<div class="ftm">FTM</div>
<div class="ftm">FTM</div>

<div class="nonbinary">Non Binary</div>
<div class="nonbinary">Non Binary</div>
<div class="nonbinary">Non Binary</div>
<div class="nonbinary">Non Binary</div>
<div class="nonbinary">Non Binary</div>
<div class="fluidqueer">Fluid Queer</div>
<div class="fluidqueer">Fluid Queer</div>
<div class="fluidqueer">Fluid Queer</div>
<div class="fluidqueer">Fluid Queer</div>
<div class="fluidqueer">Fluid Queer</div>

<input class="filter-btn" type="button" value="MTF" data-target="mtf">
<input class="filter-btn" type="button" value="FTM" data-target="ftm">
<input class="filter-btn" type="button" value="Non Binary" data-target="nonbinary">
<input class="filter-btn" type="button" value="Fluiq Queer" data-target="fluidqueer">

In your scenario, a common selector can be

var $all = $('.fandomboxes div');

Therefore, the updated code would look like this:

  $(".filter-btn").click(function() {
    var $all = $('.fandomboxes div'),
    className = $(this).attr('data-target');
    if ($all.not("." + className).is(":visible")) {
      $("." + className).show();
      $all.not("." + className).hide();
    } else {
      $("." + className).hide();
      $all.not("." + className).show();
    }
  });

Answer №2

querySelectorAll() is the method that locates classes.

Due to how classes and IDs differ in their functionality (multiple elements can have the same class while only one can have a specific ID), this method returns a collection of elements rather than just one.

In JavaScript, the style property only applies to individual elements, so you must loop through them:

var elements = document.querySelectorAll('<yourclass>');

elements.forEach(function(element) {
    element.style.<yourproperty> = <yourvalue>
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am having trouble creating a modal box for my gallery images

I'm currently working on a PHP dynamic site and I've encountered an issue with my gallery code. For some reason, the modal box is not showing up when I click on the gallery images. Can anyone please assist me in resolving this problem? var mod ...

Incorporate a JavaScript message using C# code in the backend

I am looking for a code snippet to execute a JavaScript function called recordInserted() that displays an alert, within the add_Click method in my code-behind file. Here is the relevant section of my code: protected void add_Click(object sender, EventArgs ...

elementToBeClickable is not supported by webdriverio

I am having some trouble with the 'waitForEnabled' function as it does not seem to behave like Webdriver's elementToBeClickable. Is there anyone who can provide some guidance on how to use this API effectively? ...

Issue with date: date.toLocaleTimeString function is invalid

I'm currently working on creating a time display component using hooks, but I'm running into an issue with the error message "TypeError: date.toLocaleTimeString is not a function." As a newcomer to this technology, any guidance would be greatly a ...

How to Style an Element Based on Fragment Identifier in Href Attribute Using CSS

I've implemented the tabview feature from the YUI3 library. This is how the markup code appears: <div id="demo" class="yui3-tabview-content"> <ul class="yui3-tabview-list"> <li class="yui3-tab yui3-widget yui3-tab-selected"> ...

When a user clicks, they will be directed to the specific product page using Angular UI router

On my homepage, I have a JSON feed where all the products are displayed. When clicking on a specific product image, I want it to redirect to a separate page showing only that particular product. I understand that changes need to be made in the singleproduc ...

Introducing a new div element completely disrupts the overall layout

Take a look at the code I have provided below. http://jsfiddle.net/xymgwonu/3/ Everything was working perfectly fine until I introduced a new div with the class name <div class="bubble"></div>. This caused some issues with the overall design. ...

Execute the function once the audio has finished loading

I need help running a function once an audio file has finished downloading. This is my JavaScript code: // https://freesound.org/people/jefftbyrd/sounds/486445/ var audioFile = "https://raw.githubusercontent.com/hitoribot/my-room/master/audio/test/test.m ...

The JavaScript for loop using .appendChild() is inserting the values of the final object, represented as [object object], into the HTML document

$(document).ready(function () { GetDetails(); }); function GetDetails() { let albumlist = document.getElementById("album-list"); $.ajax({ url: '/Store/browseajax', type: 'GET', data: { id: '@ ...

Is it possible to transfer data between the beforeSend and success functions within the jQuery .ajax method?

The Issue When utilizing AJAX to request data from a remote API, the asynchronous nature of the request means that responses come back whenever they are ready. The challenge arises when making multiple calls to the same API with different parameters, as i ...

What causes npm start to fail with a CORS error, but run successfully with HOST=127.0.0.1 npm start?

Currently, I am in the process of creating a basic application that utilizes Flask for the backend and React for the frontend. An issue arises when attempting to initiate my React application through npm start, as it triggers a CORS error. Strangely enough ...

I encountered an issue with adding a console log in the getStaticProps() function that resulted in the error: SyntaxError: Invalid Unicode escape sequence at eval (<anonymous>

Welcome to my users.js page! import React from 'react' const displayUsers = ({users}) => { return ( <> { users.map(user => { return <div key={user.id}> {user.name} </div> }) } </&g ...

What is the best way to transfer information from JavaScript to a JSON database using the fetch API?

Within the userDB.json file, it appears as follows; [{ "username": "john", "xp": 5 }, { "username": "jane", "xp": 0 } ] Inside the app.js file ; async function getUsers() { le ...

What is the best method for sending a document to a web API using Ajax, without relying on HTML user controls or forms?

I have successfully utilized the FormData api to upload documents asynchronously to a web api whenever there is a UI present for file uploading. However, I now face a situation where I need to upload a document based on a file path without relying on user ...

We are creating a table in JavaScript and mistakenly adding an unnecessary tbody

I am currently utilizing a combination of plain JavaScript and Jquery in order to dynamically generate a table. The issue arises when I attempt to use a for loop to iterate through the data obtained from an Ajax request, as it fails to create new rows. To ...

Emphasize cells and headers when a cell's value deviates from its initial value

I implemented cell editing in my primeng table. Here is the code: <div class="card"> <p-table [value]="products" dataKey="id" [tableStyle]="{ 'min-width': '50rem' }"> <n ...

Fade effect not working with Bootstrap Modal

I am encountering an issue with the Twitter Bootstrap modal while trying to display post details on WordPress. The problem is that when the modal opens, the entire screen turns grey and nothing in the modal is clickable. I can only exit this mode by pressi ...

Updating a table in Laravel 5.2 by adding a new record using AJAX without the need to refresh the page

My inquiry pertains to a specific issue. I have a straightforward form in Laravel where some fields trigger pop up windows with tables. I aim to enable the popup window to display newly added records without requiring a page reload and reopening the popup ...

What is the process for launching a new terminal within Node.js?

I'm seeking advice on creating a secondary window in my node.js application where I can output text separate from the main application. Imagine having a main window for displaying information and a secondary window specifically for errors that closes ...

Database Submission of Newsletter Information

I recently grabbed the following code snippet from a YouTube tutorial (shoutout to pbj746). Everything appears to be functioning correctly except for one crucial issue - the submitted data isn't showing up in the database! I've thoroughly checked ...