When the CSS class of a DIV is set to X in jQuery, the script will hide all other DIVs with a

Just starting to explore jQuery and still fresh on JS knowledge, I have the desire to craft a jQuery script.

To begin with, here is my HTML snippet:

<div id="user-controls">
    <div class="choice" id="choice-all" onclick="showAll();">All</div>
    <div class="choice" id="choice-asus" onclick="justASUS();">ASUS</div>
    <div class="choice" id="choice-htc" onclick="justHTC();">HTC</div>
</div>

<div id="devices">
    <div class="android asus">Nexus 7</div>
    <div class="android htc">One S</div>
    <div class="android htc">One X+</div>
    <div class="android asus">Transformer Prime</div>
    <div class="winph htc">Windows Phone 8X</div>
</div>

An ideal jQuery code would be able to carry out the following actions:

  1. Clicking on the #choice-asus DIV should hide all DIVs with the .htc class

  2. Clicking on the #choice-htc DIV should hide all DIVs with the .asus class

  3. Clicking on the #choice-all DIV should set all DIVs to display="inline-block" (the default setting upon page load)

I've made an attempt with the code below, but unfortunately, it's not yielding any results.

$(document).ready(function(){
    $("#choice-htc").click(function(){
        $(".htc").hide();
    })
});

Your assistance will be greatly appreciated. Best regards, Dylan.

Answer №1

There are so many options to choose from! Check them out here

    $(function(){
        $("#user-controls").on('click','div',function(){
           var showClass = this.id.split('-')[1],
               filtering = showClass === "all" ? 'div': '.' + showClass;
           $("#devices").children().show().not(filtering).hide();
         }); 
     });

Answer №2

Have you tried implementing jquery in your code?

Check out the demo here

$('#choice-all').click(function(){
  $('.htc, .asus').show();
});

$('#choice-asus').click(function(){
  $('.asus').show();
  $('.htc').hide();
});

$('#choice-htc').click(function(){
  $('.htc').show();
  $('.asus').hide();
});   

Answer №3

Check out the demo!

$(document).ready(function(){   
    $(".option").click(function(){
         $(".iphone,.blackberry").hide();
        if($(this).attr("id")=="choice-all"){
            $(".iphone,.blackberry").show();
        }else if($(this).attr("id")=="option-samsung"){
            $(".samsung").show();
        }else if($(this).attr("id")=="option-lg"){
            $(".lg").show();
        }
    });
});

Answer №4

In order to maintain simplicity and organization, utilizing a solution like the one provided is advised.

$(function(){
    $('#choice-asus').on('click', function(){
        $('#devices > div:not(.asus)').hide();
    });
});

This code essentially states that when you click on #choice-asus, any divs in #devices without the class asus will be hidden.

You have the flexibility to customize this code according to your specific requirements. Additionally, it is recommended to employ jQuery's .on() method rather than other event handlers like click/bind for better functionality.

Answer №5

$(document).ready(function(){
    if($('div').attr('class')=='X')
    {
         $('div').not($(this)).css('display','none');
    }
});

Answer №6

Feel free to experiment with the code below-

function displayAllItems(){
    $("#products div").show();
}
function showOnlyASUS(){
    $("#products div").hide();
    $("#products .asus").show();
}
function showOnlyHTC(){
    $("#products div").hide();
    $("#products .htc").show();    
}

Check out the live demo here.

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

What causes an exception to be thrown even after being caught in an async function?

Even if an exception is caught, the remaining code will still run. function problematic(){ //throw new Error('I am an exception') return Promise.reject("I am an exception") } ( async function (){ let msg = await problem ...

Choosing a value from a dropdown automatically based on the selection of a specific value from another dropdown

Currently, I am working on a project that involves selecting a value from a dropdown menu based on the selection from another dropdown menu. var gender1 = document.querySelector("#gender1"); var gender2 = document.querySelector("#gender2"); gender1.add ...

Utilizing ng-if within ng-repeat for dynamically generated option tags in HTML and AngularJS

I am using AngularJS to create a dropdown menu with select and option tags. The menu is referencing a model and looks like this: <select id="edit-location" class="" ng-model="packageLoc"> <option ng-repeat="x in loc" value="{{ x.locationId }} ...

Discovering elements containing a particular value within a deeply nested array of indefinite depth

I am working with an array containing objects that may have unknown and varying nesting depths. Here is an example of such an array: let exampleArray = [ { id: 'some-id', label: "Item 1", children: [ { id: &a ...

Limits on zooming with THREE.js Orbit controls

I've encountered an interesting limit while using Orbit controls. The zooming functionality is tied to the radius of the spherical coordinates of the camera in relation to the orbiting axis. Here's how it functions: Whenever the user scrolls, t ...

Stop the div underneath from scrolling on iOS Safari

I have a div that has a height of 100%, equivalent to 70% of the viewport height, with an overflow:scroll property. Now I would like to add an overlaying div that touch devices can use to scroll the entire page instead of just the div. I attempted to cre ...

Using VB.NET to run JavaScript through Selenium's ChromeDriver

I've tried various methods in C# but I can't seem to get them working in VB.NET. It's possible that I'm not initializing it correctly. My goal is to run javascript on a loaded URL using the chromedriver. This is what my code looks like ...

Looking to display or conceal a text box with a date picker based on the selection of a specific value from a drop-down menu

I have a dropdown with two options: Indian and Others. When I select Others, I want to display three textboxes - two with date pickers and one with a simple text input field. I have tried writing the following HTML code but I am unable to get the date pick ...

Steps for generating an observable that mirrors the structure of an observable array

I am in the process of creating an observable array using JSON data retrieved from the server. var ViewModel = function (data) { var self = this; self.list = ko.observableArray(data); self.selected = ko.observable(); } ...

Ways to arrange specific columns within a table

I am facing an issue with aligning text in a table properly. In my table, I have two columns - first column and second column, both with colspan="4": It is supposed to look like this: <tr> <td colspan="4"> First column </td> ...

Ways to create adaptive images using Bootstrap 5

On my website, there are some cards that look great on large and medium screens. However, on small screens, the images appear stretched vertically! I am using Bootstrap 5 and here is the code snippet: <div class="col-12 mb- ...

The presence of elements set to visibility:hidden can result in the creation of

I have encountered a situation where a hidden popup using "visibility: hidden" still occupies space on the screen. Unfortunately, I do not have control over the coordinates of this element as they are automatically calculated by Primefaces control. View J ...

Why is my ASP.NET MVC model not being updated when making an AJAX post request?

Currently, I am working on an asp.net MVC application. Within my view page, there is a textbox implemented using the following code: @Html.TextBoxFor(m => m.Id, new { @class = "form-control", @readonly = "readonly" }) Furthermore, in the form submissi ...

What makes the middle element in a sorted array the majority element?

While working on this particular problem on Leetcode, I came across a solution that left me puzzled. The solution suggested to "sort the array and the middle element will be the majority." My question is: "Why is the middle element of a sorted array c ...

Centered label above an inline input form

I'm struggling with aligning inputs under long labels in a form. I want the input fields centered under each label while keeping them inline. The desired look is shown below: https://i.sstatic.net/itJCY.png The current code I have is not achieving t ...

Extract the body.req object within a loop in a Node.js application

I'm looking to efficiently parse and save the body of a POST request using Mongoose in Node.js. Is there a way to use a for loop to accomplish this task, rather than manually saving every property? My ideal solution would involve something like: for ...

Remove the tooltip in case the title attribute is blank

I am currently working on adjusting this code to prevent the #tooltip from appearing if the title attribute of my link is empty: this.tooltip = function(){ /* CONFIG */ xOffset = -23; yOffset = -150; // these 2 v ...

Searching for an equivalent to AdRotator within the .NET framework

Currently, I am developing a website that features rotating testimonials. I am interested in finding a solution similar to the AdRotator class available in .NET. However, instead of rotating images, I need a method to rotate formatted text blocks using HTM ...

transform constant values into API requests using React

The sample dataset mentioned will be retrieved from a backend API call handled by Flask. The API has already been configured on the backend. const rows = [ { name: "XYZ", age: "12", email: "<a href="/cdn-cgi/l/emai ...

At what stage in the code does the loop conclude?

While researching Selenium Webdriver framework best practices on GitHub, I came across the following code snippet: async function waitForVisible(driver, locator, retries = 3) { try { const element = await driver.findElement(locator); ...