Strategies for selecting elements in jQuery that are displayed and not hidden

Here is the structure of my HTML code :

{# Navigation for xs screens #}
<div class="small-screen-nav hidden-lg hidden-md hidden-sm col-xs-12" style="padding: 0;">
    <ol class="breadcrumb" style="padding: 0px 7.5px">
        <li><a href="#" id="make" class="active">Make</a></li>
        <li><a href="#" id="model">Model</a></li>            
    </ol>
</div>

{# Navigation for sm, md, lg screens #}
<div id="calculation-menu" class="col-lg-2 hidden-xs">
    <div class="list-group">
        <a href="#" id="make" class="list-group-item active">Make</a>
        <a href="#" id="model" class="list-group-item">Model</a>
    </div>
</div>

The jQuery code I am using is as follows :

<script>
    $(document).ready(function () {
        $('#make').removeClass('active').html("Some text");
        $('#model').addClass('active');
    })
</script>

However, there is an issue where the code is targeting the hidden navigation. On large screens, the first navigation is hidden, but the jQuery code continues to target it instead of the visible navigation (second one).

Does anyone have a solution to this problem?

Answer №1

Make Sure Your id Attributes are Unique

It's important to check that your id attributes are unique because they need to be distinct by definition. Not having unique ids can lead to various problems and conflicts in your code.

Instead of using the same id attribute, consider using a class attribute or a data-* attribute to manage this better (see example below) :

<!-- Mobile -->
<div class="small-screen-nav hidden-lg hidden-md hidden-sm col-xs-12" style="padding: 0;">
    <ol class="breadcrumb" style="padding: 0px 7.5px">
        <li><a href="#" class="active" data-make>Make</a></li>
        <li><a href="#" data-model>Model</a></li>            
    </ol>
</div>

<!-- Small, Medium, and Large -->
<div id="calculation-menu" class="col-lg-2 hidden-xs">
    <div class="list-group">
        <a href="#" class="list-group-item active" data-make>Make</a>
        <a href="#" class="list-group-item" data-model>Model</a>
    </div>
</div>

You can then use this code as intended:

<script>
    $(function () {
        $('[data-make]').removeClass('active').html("Some text");
        $('[data-model]').addClass('active');
    });
</script>

Take Advantage of the :visible Selector

If you specifically want to target only the visible element, you can utilize the :visible selector in jQuery like this:

// This will select only the visible element with the data-make attribute
$('[data-make]:visible')

Answer №2

It is strongly advised to avoid using duplicate id's as it can create a lot of issues. However, if you are in a pinch and need a quick solution to target both elements, you can utilize the attribute selector:

Instead of using $('#make'), you can use $('[id="make"]').

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

django Ajax GET request could not locate the specified URL

I'm facing an issue while trying to pass parameters through Ajax with Django 1.11. The error message states: Not Found: /enquiry/followup_alter/. Below is the relevant code snippet. Error: Not Found: /enquiry/followup_alter/ Ajax: $(docume ...

h1 tag set for jQuery AJAX activation

Currently working on a website that heavily relies on ajax. Encountering an issue that hasn't been solved through online resources. Now, I'm sharing my function for fetching a page: function loadTemplate(name, replaceWholePage = true){ $.wh ...

Uncovering hidden links in a menu with Python Selenium and JavaScript

Can someone provide guidance on how to activate the JavaScript submenu associated with this button, "x-auto-54"? <table id="x-auto-54" class=" x-btn avtar-x-btn x-component x-btn-noicon x-unselectable " cellspacing="0" role="prese ...

What is the proper way to incorporate html entities in my specific situation?

In my application, I am attempting to incorporate double macron characters. My current method involves using the &#862; entity, like this: t&#862;t, which results in t͞t. However, I have encountered issues with reliability, as sometimes the ...

Prevent the need to keep deleting text when entering data into selectize.js <select>_dropdown

I am working with a single choice <select> element that has been enhanced using selectize.js. This <select> element already has an option pre-selected as the current value. To change this value, users must: Click on the drop-down control, Pr ...

retrieving a value of an attribute within an AngularJS directive

I have created a directive configModule.directive('iMemoryDiv',function () { return { restrict: 'E', scope: {}, replace: true, templateUrl: '/memoryDiv.html', link: function(scope, el ...

Having trouble getting the show/hide div feature to work in a fixed position on the

Trying to show/hide a div using jQuery isn't working when the div is wrapped in a position:fixed element. However, changing it to position:relative makes the show/hide function work again. You can see an example of the working version with position:r ...

Tips for organizing the outcome of a seamless web scraping operation with Apify and Puppeteer

Extracting data from a table on the designated URL using Apify and Puppeteer is my current goal: https://en.wikipedia.org/wiki/List_of_hedge_funds The desired outcome should be an array of objects. Each element in the array must represent a <tr> ro ...

Utilizing jQuery to retrieve data attributes from an HTML Select element, and incorporating an SQL query to dynamically populate additional HTML input fields within Classic ASP

From the title, you can probably gather a bit about the issue I'm facing. I have limited experience with classic ASP, but it's still used at my workplace. They've asked me to make some edits that involve adding validation for input fields. S ...

Learn how to use Angular2 or TypeScript to display 'unsubscribe' and 'subscribe' text on a toggle button

I'm working on a toggle button that initially displays the word subscribe on the thumb. When the toggle is disabled, I want it to show unsubscribe instead. Can someone please help me achieve this functionality? Here's the code snippet: <md-s ...

In order to showcase an image ahead of another (stay tuned),

Help! I'm facing a dilemma here. I have an abundance of adorable animal images with unique facial expressions, but there's one problem - the eyes are hidden! I desperately want to showcase those captivating eyes. This is what my code looks like. ...

Scripting in jQuery to create dropdown menus

I've encountered a unique issue on my website where a user's selection from one list should update the values in another list: <form id="form1"> <div> <select id="workField"> <option value ...

Customize the position of the date picker for HTML native <input type="date">

I have implemented the HTML native input date element (found here- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date) and encountered an issue in Safari on macOS where my date picker is being displayed off-screen. How can I resolve this ...

Having trouble uploading a file to Laravel using the jQuery .post method?

Here is a snippet of my HTML code: <input type="file" class="form-control" name="file-name" id="file-id"> This is the JavaScript function that is meant to send the file to an API: var file = $('input#file-id').val(); $.post('my/url/ ...

I encounter a black screen issue while attempting to rotate a three.js cube

How can I rotate a cube around all three axes (x, y, z) using the code snippet provided below? ` <html> <head> <title>CM20219 – Coursework 2 – WebGL</title> <meta charset="utf-8"> < ...

How can you use JavaScript to create a JSON object using values from an HTML form textarea and then send

I need to create an HTML form that will send specific information in the Http-request body. { “info” : { “id” : “123” “text1” : <data from html text-box> } Therefore, my goal is to convert the provided data into a JavaScri ...

`json: Alert not displaying response data`

Currently, I am utilizing the following Ajax code to retrieve data from the server. $.get("http://***/umbraco/Api/SomeApi/SignIn",{apiVersion : 1,email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ee0efe3ebcee9e3efe7e2a0ed ...

Advanced AJAX image gallery with a touch of fancybox

I'm attempting to implement a fancybox image gallery using ajax for the first time. My knowledge of fancybox and jQuery is limited, but here's what I've managed to put together so far. Take a look at the gallery link below; <a class="fan ...

Reposition HTML content using regular expressions

My objective is to locate a block of HTML that contains comments and relocate it after the header section. The comment itself remains constant, but the content within the block varies across different pages and needs to be replaced using Dreamweaver' ...

Creating a dynamic menu system using ASP.NET, JQuery, and Suckerfish for optimum functionality

I want to create a dynamic menu from a table using the Suckerfish CSS menu and JQuery. I'm following this example as my guide: Suckerfish menu with ASP.NET and JQuery. Currently, I have managed to make it work by manually adding links, similar to what ...