Organizing HTML elements based on their class names, especially when an element has multiple classes assigned

Hey there, I've been working on an artist page that showcases multiple artists, each with a portfolio image and some detailed information. My goal is to have buttons at the top of the page that, upon clicking, will sort the artists displayed.

To achieve this, I assigned specific classes to each type of artist. When a button is clicked to filter by a specific type, it hides all artists not belonging to that type. For example, selecting 'Music' would hide all 'Photography', 'Film', and 'Graphic' artists, leaving only the music artists visible.

The issue I'm facing is with artists who fall into multiple categories. For instance, if an artist is classified as both 'Music' and 'Photography', selecting 'Music' would unintentionally hide them due to their dual classification. The challenge lies in displaying artists who belong to more than one genre.

Here is a snippet of the HTML code for each artist element:

<div class="col-md-4 col-lg-4 musicartist">
        <div id="artist1">
          <div class="arthov">
            <img class="img-circle img-responsive" src="../img/artists/music/Lexxicon.png">
            <div id="recentwork"><p><a href="#">View Artist</a><p></div>
          </div>
            <p><strong><h3>Lexxicon</h3></strong>R&B | Toronto, ON<br><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d4958534952584e59524a535e527d5">[email protected]</a></strong></p>
        </div>
      </div>

Below is the JavaScript script filter function used to hide all elements of a specific class:

<script>
function filterMusicArtists() {
  var appBanners = document.getElementsByClassName('musicartist'), i;

  for (var i = 0; i < appBanners.length; i ++) {
      appBanners[i].style.display = 'none';
  }
}
</script>

Lastly, here is the code for the buttons at the top of the page that filter artists. These buttons trigger the JS methods to hide artists of other types:

<div class="col-md-2">
          <div class="music">
            <div class="musicgenre" type="button" onclick="showMusicArtists();filterPhotographyArtists();filterFilmArtists();filterOtherArtists();filterGraphicArtists();filterFashionArtists();">Music</div>
          </div>
        </div>

While I'm familiar with HTML and CSS, JavaScript is newer to me. I understand that my current approach may not be the most efficient or ideal, so any guidance on improving it would be greatly appreciated. I'm determined to find a solution to display artists with multiple art genres!

Thanks!

Answer №1

To start, hide the elements with classes representing categories that were not selected, and then reveal the ones that were clicked on. This will result in displaying all artists belonging to the category you selected.

For example:

$('.painting, .sculpture').hide();
$('.photography').show();

This code will display artists who have both the painting and photography classes or both the sculpture and photography classes, excluding those with only painting or only sculpture.

The non-jQuery solution is also simple. Just use document.getElementsByClassName to target your elements and set their style.display accordingly.

Answer №2

The reason for this issue is that you are attempting to conceal all artists except the selected one, but your code is actually hiding the chosen type of artists.

 <script>
function filterMusicArtists(type) {

var appBanners = document.getElementsByClassName('artist');

for (var i = 0; i < appBanners.length; i ++) {
  var currentArt = appBanners[i];
    if ( currentArt.classList.contains(type) )
    {
       if (!currentArt.hidden){
          currentArt.hidden=true;
       }
   }
  }
}
</script>

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

Issue with wrapper not aligning correctly at the top of the screen

I keep noticing a gap between my wrapper and the top of the page. Despite trying multiple solutions, none seem to work for me. The background image covers the entire background and is aligned at the top perfectly, but the wrapper with its own background a ...

Prevent the submit button from being clicked again after processing PHP code and submitting the form (Using AJAX for

I've set up a voting form with submit buttons on a webpage. The form and PHP code work fine, and each time someone clicks the vote button for a specific option, it gets counted by 1. However, the issue is that users can spam the buttons since there i ...

Incorporate a JSON file into the Webpack output separately from the bundle.js file

Is there a way for my webpack application to read a JSON file at runtime without including it in the bundle.js after packaging? I want the JSON file to be available in the package folder but not bundled with the rest of the code. How can I achieve this? ...

Simple Method To Dynamically Align jQuery LightGallery Thumbnails On a Responsive CSS Website

Can anyone assist me quickly? I've implemented everything but am facing a slight issue with the centering of my ul code. I've tried various solutions without success. Here is my code, any advice would be greatly appreciated (I may sound stressed ...

What is the best method for positioning span content above all other elements without having it wrap around them?

Each form element on my page is accompanied by a span that displays an error message, if applicable. The layout consists of two columns: left and right. I am struggling to make the span display seamlessly from the left column all the way across the page wi ...

Autocomplete with Avatar feature in Material UI TextField

Is it possible to display an avatar in the text field of the autocomplete material-ui component when using the getOptionLabel prop, which only accepts a string? The expected UI shows a profile picture and name for each option. Can we achieve the same thi ...

How come the html element doesn't have a default height of 100%?

Is there a reason why the html element is not automatically set at 100% height by default? Can you think of any scenarios where having it take up less than the full height of the window would be beneficial? html { height: 100%; } [Update] I modified th ...

What is the best way to utilize the node.js module passport-google?

I'm currently working on a node.js web application that prompts users to sign in using their Gmail account. While following instructions provided at this website, I modified the URL from www.example.com to localhost and launched the application. Howev ...

The issue I encountered with Angular's Mat-Select component is that the openedChange

When a user opens the mat-select, I am attempting to set CSS style using custom code. However, I am encountering an undefined error. Upon checking in the console, I noticed that the panel value is returning undefined. Can someone please advise me on how to ...

The D3 path is generating an unexpected output of 0px by 0px, causing the map not to display properly. I am currently unsure how to adjust the projection to

I am currently working on creating a world map using D3. I obtained the JSON file from the following link: https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json Below is the code snippet I'm using: // Defining SVG dimensio ...

The Array map function is not displaying the list within a React component that is based on a Class

I am having trouble displaying a list of food items in my Parent component FoodBox.js and its child component FoodItems.js. I am using the map() method, but the <ul> element is showing up empty. Here is my code for FoodBox.js const FOOD_ITEMS = [ { ...

Discovering the value of a chosen star and saving it in a database with the help of jQuery or JavaScript

When a user clicks on the 3rd star in the Jrate Plugin, I need to retrieve the value of 3. This can be achieved using the jRate onSet option. Below is my HTML: <div id="jRate"></div> And this is my JavaScript code: $("#jRate").jRate({ ...

What is the best way to retrieve the ID of the most recent div element added using AJAX and jQuery?

Initially, I have a div with a pre-set ID. Then, I use an AJAX call to add more divs into this container. How can I retrieve the IDs of these dynamically added divs using jQuery? For example: <div class="main"> <div id="0" class="take">t ...

In Javascript, assign default values to an array and update them with new values upon the click of a

My goal is to create a quiz that populates an array. Initially, the quiz is empty but I aim to assign it a default value. This serves as my question navigation: /** * * @param {int} question * @returns {QuizPart} ...

Guide to setting up a Node, Express, Connect-Auth, and Backbone application architecture for server-side development

As someone who primarily works on the client-side, I have recently ventured into the realm of server-side JavaScript. My initial plan for my first Node.js application involves a server-side setup that primarily serves an empty shell along with a plethora o ...

Passing data from an Express middleware to a Jade template

My KeystoneJS app is all set up, using Express and Jade. The default.jade file sets up a fullscreen background image along with various imports, the header, and footer of the site. I am attempting to rotate the image based on a selection of images stored ...

The document ready event does not fire upon page load, but can be triggered using the Developer Tools Console

When the ajax call is successful, the li element gets added to the ul. $.ajax({ .. success: function (response) { response.data.forEach(function (x) { $("#ulMain").append('<li class="liSub">' + x + &apo ...

Jquery Error in Bootstrap and DataTables Integration

My knowledge of frontend coding is limited, so please bear with me. Initially, my website was using MVCContrib grid along with its own CSS style. Recently, I switched to Bootstrap which caused MVCContrib to stop working. I've been struggling to integ ...

Navigating router queries within Nuxt: A step-by-step guide

One of the challenges I am facing is passing value parameters in my URL with the mounted function looking like this: mounted () { this.$router.push({ path: '/activatewithphone', query: { serial: this.$route.params.serial, machin ...

PHP is not processing the HTML form I submitted

HTML: <form method="post" action="create.php"> Job #: <input type="text" name="jobnum"> <br> Program: <input type="text" name="program"><br /> Ship Date: <input type="text" name="shipdate"><br /> Description: < ...