Ways to display a specific element by its id while concealing others

I have a collection of items in a list, each with unique ids:

<ul>
<li id="item1">Item 1</li>
<li id="item2">Item 2</li>
<li id="item3">Item 3</li>
</ul>

<div class="item1">This is Item 1.</div>
<div class="item2">This is Item 2.</div>
<div class="item3">This is Item 3.</div>

When I click on an item in the list, I want the corresponding div (with the same class) to be displayed while hiding the others. I attempted using some JavaScript code but it doesn't seem to be functioning properly.

$('.photo-select li').click(function() {
            var itemId = $(this).attr('id');
            $('.productinfo:not(.'+itemId+')').hide();
            $('.productinfo:is(.'+itemId+')').show();
});

Answer №1

Initially, your code contains duplicate id attributes, which is not allowed. Each id should be unique within the document. To address this issue, you can utilize common classes and a data attribute to establish the relationship between the a and div elements. Here's an example:

<ul>
    <li class="foo" data-rel="test1">Test1</li>
    <li class="foo" data-rel="test2">Test2</li>
    <li class="foo" data-rel="test3">Test3</li>
</ul>

<div class="content" id="test1">Test 1, okay!</div>
<div class="content" id="test2">Test 2, okay!</div>
<div class="content" id="test3">Test 4, okay!</div>
.content {
    display: none;
}
$('.foo').click(function() {
    $('#' + $(this).data('rel')).show().siblings('div').hide();
})

Sample implementation

If desired, you can avoid using data attributes and id by establishing the link based on the element's position within its container:

<ul>
    <li>Test1</li>
    <li>Test2</li>
    <li>Test3</li>
</ul>

<div id="content-container">
    <div>Test 1, okay!</div>
    <div>Test 2, okay!</div>
    <div>Test 4, okay!</div>
</div>
#content-container > div {
    display: none;
}
$('li').click(function() {
    $('#content-container').find('div').eq($(this).index()).show().siblings().hide();
})

Interactive demo

Note that although the second approach is more concise, it may lack robustness depending on the structure and potential changes in your HTML. Both methods are valid solutions, so choose what best suits your needs.

Answer №2

Web browsers are designed to only recognize the first instance of an ID, storing them in a quick lookup with only one element for each key value.

To work around this limitation, it's recommended to utilize classes and data- attributes:

<ul>
<li class="clickme" data-target="test1">Test1</li>
<li class="clickme" data-target="test2">Test2</li>
<li class="clickme" data-target="test3">Test3</li>
</ul>

<div id=test1">Test 1, okay!</div>
<div id=test2">Test 2, okay!</div>
<div id=test3">Test 4, okay!</div>

This then translates into the following code snippet:

$('.photo-select .clickme').click(function() {
        var productid = $(this).data('target');
        $('.productinfo').not(productid).hide();
        $(productid).show();
});

While these three lines of code can be condensed further, they have been kept concise for clarity purposes.

Another important consideration is concealing the initial states. This can be achieved by adding style="display:none" or managing their visibility through CSS.

Answer №3

Your solution is almost complete, just a few minor tweaks needed:

$('li.photo-select').click(function() {
    var itemID = $(this).attr('id');
    $('div.item-details:not(.' + itemID + ')').hide();
    $('div.item-details.'+itemID).show();
});

Check out the demo

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

Ensure that the loop is fully executed before proceeding with any additional code

Check out this code snippet I've been developing: let arrayB = []; for (let index = 0; index < res.length; index++) { let fooFound = false; const dynamicFoo = require(`./modules/${res[index]}`); rest.get(Routes.applicationCommands("BLA ...

Having trouble with the sleep function in nodejs?

Hey there! I'm currently working on a Node.js function that sends requests using array.map. However, I'm facing a challenge with making the function wait for 4 minutes when an error occurs before sending the next request. I've attempted to u ...

Customize the font color in Material UI to make it uniquely yours

How can I customize the default Text Color in my Material UI Theme? Using primary, secondary, and error settings are effective const styles = { a: 'red', b: 'green', ... }; createMuiTheme({ palette: { primary: { ...

Retrieve the key{index} property from the .map method in React for the element that was just clicked

I am facing an issue with my code const Component = () => { const [Clicked, setClicked] = useState(false); const handleClick = (prop, e) => { console.log(prop); } return ( <div> {arrayCard.map((item, i) => { ...

Is CSS the only way for Python Selenium to locate an element?

My attempt to log in to the Apple website using Selenium has hit a roadblock. When I try to locate the 'sign-in button' using find_element_by_id, an error pops up indicating it's actually a CSS selector. What exactly does that imply? I was ...

Tips for displaying a div element alongside a button within a reactJS table

How can I position a div element next to a button in a ReactJS table? I have a table component where I want to display some options in a small window that closes when clicked outside. Options : https://i.sstatic.net/sT8Oi.png Action button in the table ...

Guide to turning off the pinch-zoom feature on Windows 8 laptops

I'm currently working on a Windows 8 desktop application where I am using C#, JavaScript, and HTML5. Specifically in the C# portion, I am utilizing the WebView object. My goal is to disable pinch-zoom within my application. I already know how to achi ...

Using a wildcard (*) to select elements with JQuery

I'm just starting to learn about JQuery and could use some help. I want to select multiple elements but I only know part of their Ids: for example: <div id="element32422455">Some content</div> <div id="element68475124">Some content& ...

I am encountering errors when running NPM start

After setting up my webpack, I encountered an error in the terminal when attempting to run the code npm start. The specific error message was related to a module not being found. Can someone please assist me with resolving this issue? > <a href="/c ...

Learn how to incorporate an image into your Codepen project using Dropbox and Javascript, along with a step-by-step guide on having the picture's name announced when shown on the screen

Hey there, I'm in need of some assistance. I have a Codepen page where I am working on displaying 4 random shapes (Square, Triangle, Circle, and Cross) one at a time, with the computer speaking the name of each shape when clicked. I want to pull these ...

What is the best way to align the navbar items at the center in Bootstrap when mx-auto is not working?

<nav class="navbar navbar-expand-sm navbar-light"> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls ...

Deactivating Webkit Input Form Shadow

Similar Question: Looking to Remove Border on Input Boxes in Chrome? Is it possible to turn off the colorful shadow effect produced by Webkit browsers when a form field is clicked? The yellow shadow in Chrome and blue shadow in Safari can interfere wi ...

When executing a Javascript POST request to a PHP script, it succeeds when running on

I have a simple code that works fine on my website when the PHP file is linked as "/phpcode.php", but it fails to retrieve data when I place the JavaScript request on another site and use the full link. I am currently using GoDaddy as my hosting provider. ...

Navigating through a series of items in VueJS can be easily accomplished by using a

Below is the Vue instance I have created: new Vue({ el: '#app', data: { showPerson: true, persons: [ {id: 1, name: 'Alice'}, {id: 2, name: 'Barbara'}, {id: 3, name: &a ...

Combining two rows into a single cell using AG-GRID

Currently, I am utilizing AG-GRID for angular in my code. Within this grid, I have two columns available - Account.Name and Account.Surname. My goal is to display the values from these two columns within a single cell. To achieve this, I attempted the meth ...

A straightforward Node.js function utilizing the `this` keyword

When running the code below in a Chrome window function test(){ console.log("function is " + this.test); } test(); The function test is added to the window object and displays as function is function test(){ console.log("function is " + this.tes ...

Obtaining input data in Laravel through a GET request

I am currently attempting to transfer input data from a get request to a view in my controller. I'm uncertain if I'm going about it the right way, or if it's even possible. The specific data I want to transfer comes from a text field located ...

Steps to send an object array using a promise

I've put in a lot of effort but haven't found a solution that works well for me. I attempted using promise.all and setting the array globally, but it didn't work out. My goal is to search through three MongoDB collections, match the finds, ...

Is it possible to eliminate the table borders and incorporate different colors for every other row?

Eliminating the table borders and applying color to alternate rows. Check out my code snippet: https://stackblitz.com/angular/dnbermjydavk?file=app%2Ftable-overview-example.ts. ...

Executing ASP.NET Code Behind Function Using JavaScript

I've created a web method to delete a user, which I'm trying to call from JavaScript. However, it doesn't seem to be working as expected. I am passing the selected index value from a listbox within a user control to my web method. Despite lo ...