JavaScript tag filtering system: Display only the div elements that contain all the specified classes in an array; otherwise, hide them

Can you provide some guidance on accomplishing this task?

I am looking to toggle the visibility of a div based on its classes and an array.

If the array contains the term something, then only divs with the class something will be displayed.

If the array is empty, all divs will be shown.

If the array includes both something and johnskeet, only divs that have both the something and johnskeet classes will be visible.

Answer №1

To simplify, one approach is to initially hide all divs and then utilize document.querySelectorAll() to add an 'unhidden' style to each div within the array.

Here's a useful question regarding selecting divs with multiple classes that may also be beneficial.

queryselectorAll - find an element with more than one matching class

Answer №2

If you're looking for a way to efficiently handle element selection and display in JavaScript, one approach is to dynamically generate a selector from an array. This allows you to show all the matching elements while hiding the rest by default:

JavaScript

const classes = ['foo', 'bar', 'baz']
     ,selector = classes.map(x => '.' + x).join('')
$(selector).show()

CSS

div {
  display: none;
}

Take a look at the JS Fiddle demo for more information.


Alternatively, if you're working with a large number of elements, it may be more efficient to generate a custom style sheet in JavaScript:

const classes = ['foo', 'bar', 'baz']
     ,selector = classes.map(x => '.' + x).join('')
     ,$style = $(`<style>div {display: none;} div${selector} {display: block;}</style>`)

$('head').append($style)

To undo this styling, simply remove the <style> element by using $style.remove().

Check out the JS Fiddle demo to see this in action.

Answer №3

If the elements are initially visible, you can simply hide the ones you don't want to show. You can achieve this by adding a stylesheet:

var rule = array.map(c => 'div:not(.' + CSS.escape(c) + ')').join()
           + '{display:none}';
sheet.insertRule(rule, 0);

var array = ["something", "johnskeet"];
var rule = array.map(c => 'div:not(.' + CSS.escape(c) + ')').join() + '{display:none}';
var style = document.createElement('style');
document.head.appendChild(style);
var sheet = style.sheet;
sheet.insertRule(rule, 0);
<div class="foo">foo</div>
<div class="something">something</div>
<div class="something johnskeet">something johnskeet</div>
<div class="something foo bar johnskeet">something johnskeet foo bar</div>

However, if some elements are already hidden, you may need to set the desired display with higher specificity. Some elements are block-level by default, while others are inline-level. jQuery's toggle function can help detect this:

$('div').each(function() {
  $(this).toggle(array.every(c => this.classList.contains(c)));
});

var array = ["something", "johnskeet"];
$('div').each(function() {
  $(this).toggle(array.every(c => this.classList.contains(c)));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">foo</div>
<div class="something">something</div>
<div class="something johnskeet">something johnskeet</div>
<div class="something foo bar johnskeet">something johnskeet foo bar</div>

Another approach could be using display: revert, but keep in mind that it's not widely supported at the moment.

Answer №4

Applying pure JavaScript, you can execute the code several times to observe the outcomes of the randomly generated classArray.

var classes = ["something","johnskeet"],
 classArray = classes.reduce((p,c) => Math.random() > 0.5 ? p.concat(c) : p,[]),
       divs = document.querySelectorAll(".something, .johnskeet");

arrayStatus.textContent = "The current classes array is: " + JSON.stringify(classArray);

for (var div of divs) div.style.display = classArray.length === div.classList.length ? classArray.every(c => [...div.classList].includes(c)) ? "" : "none"
                                                                                     : !classArray.length ? "" : "none";
.something           {background-color: paleGreen}
.johnskeet           {background-color: tomato}
.something.johnskeet {background-color: thistle}
<p id="arrayStatus"></p>
<div class="something johnskeet">SJ</div>
<div class="johnskeet">J</div>
<div class="johnskeet">J</div>
<div class="something">S</div>
<div class="something">S</div>
<div class="johnskeet">J</div>
<div class="something johnskeet">SJ</div>
<div class="johnskeet">J</div>
<div class="something johnskeet">SJ</div>

Answer №5

There is no need to complicate things.

var array = ["something", "foo"];

To transform your array into a selector that is required.

$('div').not("."+array.join(".")).hide();

Show the element that has at least one class from the array.

$('div').not("."+array.join(",.")).hide();

If dealing with a large number of elements, you can also use each().

var array = ["something", "johnskeet"];
var selector="";
$.each(array, function(key, value){
  selector += "."+value;
});
console.log(selector);
$('div').not(selector).hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">foo</div>
<div class="something">something</div>
<div class="something johnskeet">something johnskeet</div>
<div class="something foo bar johnskeet">something johnskeet foo bar</div>
<div class="dummy">dummy</div>

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

Having trouble uploading an image to firebase storage as I continuously encounter the error message: Unable to access property 'name' of undefined

Hey there, I'm currently facing an issue while trying to upload an image to Firebase storage. Despite following all the instructions on the official Firebase site, I'm stuck trying to resolve this error: Uncaught TypeError: Cannot read property ...

React and Mui are experiencing a peculiar issue where a background is mysteriously missing from a component in a specific location

Exploring React 16 and functional components with hooks Discussing Mui 4 framework Adding a background pattern to multiple login pages seems simple, right? Here is an example of a login page component: return ( <Box width={1} height={1}> ...

What is the best way to prevent the first option in a <select> element from moving up and down using jQuery?

Is there a way to make the first option in a select list non-selectable and keep it at the top when using up and down buttons? The value option should always remain on top. If "Author" is selected and the up button is clicked, nothing should change. The ...

Placing elements from an array into a customized output

Currently, I am dealing with a unique output: dAmn_Raw('send chat:Sandbox\n\nmsg main\n\nthismessage'); In my code, there exists a variable: myvariable that stores a random value selected from an array I formulated. The cha ...

Retrieving precise information from the backend database by simply clicking a button

As a new full stack programmer, I find myself in a challenging situation. The root of my problem lies in the backend table where data is stored and retrieved in JSON format as an array of objects. My task is to display specific data on my HTML page when a ...

What is the process of generating a popup panel without relying on libraries, using JavaScript and CSS?

I'm currently working on creating a popup panel that is centered on the screen with rounded corners (scrollbars are unnecessary) using jQuery min, similar to this example: https://i.stack.imgur.com/0kYO6.png My progress so far: function (package) ...

Creating a hierarchical tree structure in AngularJS by recursively traversing JSON data

I am having trouble creating a node tree from a JSON file. My index.html file should load the node tree recursively from person.json, but I'm stuck in an infinite loop. Can someone please assist me with this? app.js (function() { var app = angula ...

What is the process for integrating a gltf model into Aframe & AR.js with an alpha channel?

--Latest Update-- I've included this code and it appears to have made a difference. The glass is now clear, but still quite dark. Note: I'm new to WebAR (and coding in general).... but I've spent days researching online to solve this issue. ...

SASS malfunctioning, error messages popping up in command prompt while running gulp serve

As I develop a web app using AngularJS and Gulp, I encounter an issue where the CSS does not seem to work when running 'gulp serve'. Despite attempting to reinstall various components like node_modules, Node.js, and Gulp, the same error persists. ...

Navigate through stunning visuals using Bokeh Slider with Python callback functionality

After being inspired by this particular example from the Bokeh gallery, I decided to try implementing a slider to navigate through a vast amount of collected data, essentially creating a time-lapse of biological data. Instead of opting for a custom JavaS ...

How can I display an image from PHP on another page?

I need to display multiple images from a database on the index.php page interface. <?php while($row = $result->fetch_assoc()) { ?> <table border="1" width="702" height="149" align="center"> <tr> <td width="148"><img sr ...

CSS properties for SVG image borders not displaying correctly

I'm having trouble creating a border around a round SVG image with the class "lock feature". When I try to add the border in the CSS element ".lock feature", the text "feature" stays white and the border doesn't show up in the browser. However, i ...

Jquery Plugin fails to generate dynamic elements effectively

I developed a masking jQuery script that dynamically adds elements to an existing input element. var link = $('<a title="show" role="link" href="#" class="masker-value">show</a>'); wrapper: function() { container = $(container) ...

Switching Formview mode using javascript

Currently, I have a formview on my website and I am looking to change the formview mode using JavaScript. Specifically, I want the formview to switch between insert mode and edit mode based on different interactions with buttons. I have a repeater on my p ...

Incorporating an array attribute into a current array of elements

I am currently attempting to incorporate the days of the week into an existing array of objects. To give you a visual representation, check out this image: https://i.stack.imgur.com/0jCBF.png After filtering my array to only yield 7 results, I aim to assi ...

During the for loop, a string variable with the prefix "undefined" is

I'm currently working with a drop-down menu where I use the .Change() function to trigger a specific action. This action involves obtaining data using the getJSON method and then creating an array string for an mp3 file based on that data. The code b ...

Tips for highlighting HTML syntax within JavaScript strings in Sublime Text

Is there a Sublime package available for syntax highlighting HTML within JavaScript strings specifically? (Please note that the inquiry pertains to highlighting HTML within JS strings only, not general syntax highlighting.) Currently, I am developing Ang ...

The dictionary of parameters includes a missing value for a non-nullable 'System.Int32' parameter

Currently tackling a problem while working on an MVC 4 application. In my project, I have an entity named 'FormaFarmaceutica' which has only one field - description. Given the single field, the creation and editing views are displayed in a modal ...

Strange behavior observed with Jquery Ajax

After spending countless days on this issue, I am still unable to figure out why it's not working. Can someone please take a look and assist me? index.php <form id = "update_status" method = "POST"> <textarea id="sha ...

What is the best way to transfer a variable from a node server to a javascript client when the page is first

My web application is mainly static, but I need to dynamically send the user's username if they are logged in and the room name they specify in the URL to the client-side JavaScript upon page load. Finding a simple solution has been challenging for me ...