Exploring jQuery's class attribute: Uncovering the key-value pair trick

I am encountering difficulties in obtaining the class of my div elements, which are intended to function as tabs on a simple asp.net website. I aim to achieve this using jQuery for better control over dynamic functions in the future. However, every time I attempt to retrieve the value of the specific "selectedTab", all I receive is "undefined".
My query revolves around how I can effectively store the relevant class alongside the name of that object (which, according to my code, seems accurate), and subsequently access it.

Here are the key sections of my basic HTML structure:

<div id="t1" class="tabs"></div>
<div id="t2" class="tabs"></div>
<div id="t3" class="selectedTab"></div>
<p></p>

Below is the snippet of jQuery used:

var tabMatchList = [{
    "tab1": "tabs"
}, {
    "tab2": "tabs"
}, {
    "tab3": "selectedTab"
}];
$.each(tabMatchList, function (i, val) {
    if ($("#t3").attr("class") == val[0]) {
        $("p").append(i + " was the tab searched for");
    } else {
        $("p").append(i + " was not the tab searched for." + val[0]);
    }
});

I appreciate any assistance or guidance provided regarding this matter.

Answer №1

.attr("class") will give you the class name excluding the ., so be sure to remove that from your array:

Another thing to double-check is that your array mentions the class selectedTab, while in your HTML it appears as selectedTabs. Make sure they match.

Apart from that, note that your current code won't function correctly as it stands:

Firstly, assign names to the properties in your array of objects:

var tabMatchList = [{
    tabName: "tab1", tabClass: "tabs"
    }, {
    tabName: "tab2", tabClass: "tabs"
    }, {
    tabName: "tab3", tabClass: "selectedTab"
}];

Then proceed with the following steps:

$.each(tabMatchList, function (i, val) {
    if ($("#t3").attr("class") == val.tabClass) {
        $("p").append(" " + val.tabName + " was the tab searched for ");
    } else {
        $("p").append(" " + val.tabName + " was not the tab searched for.");
    }
});

VIEW DEMONSTRATION

Answer №2

$('#t1,#t2,#t3').each(function(index){
    if($(this).attr('class') == 'selectedTab' ){
       $("p").append(index + " was the selected tab <br/>"); 
    }else{
         $("p").append(index + " was not the tab chosen." + $(this).attr('class') + "<br/>");
    }
});

Check out the 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

Guide on adding dual horizontal scroll bars to a v-data-table (Vue / vuetify)

Currently, I am working on Vue / Vuetify and experimenting with the v-data-table component. While creating a table, I noticed that it has a horizontal scroll bar at the bottom. https://i.stack.imgur.com/noOzN.png My goal now is to implement two horizontal ...

Click event not triggering on a div component in React

I'm having an issue with an onclick event on a div that is not triggering. <div className={styles.scrollingDiv}> <div className={styles.rectangleDiv} /> <div className={styles.menuBarDiv}> ...

Change the name of a file to a name chosen by the user while uploading it to an

I'm a beginner when it comes to node.js and I'm facing an issue that I couldn't find a solution for despite looking into various related topics. My problem involves using Node.js on the server side to upload a file and rename it based on a ...

Reconfigure the Node application using Express to seamlessly access modules through route files

I recently created a basic app using npm express. After generating the app.js file, I attempted to add new modules but encountered an issue where I couldn't access them in the route files. For example, when trying to utilize the 'request' mo ...

Converting JSON data to an Excel file in an Angular application

I'm working on exporting my JSON data to an XLSX file. Despite successfully exporting it, the format in the Excel file isn't quite right. Below is the code I am using: downloadFile() { let Obj = { "data": [12,123], "date": ["2018-10- ...

Adjust the margin/padding of the Glyphicon within a Bootstrap badge

Currently, I have a glyphicon inside a badge and I want the glyphicon to have a smaller font size than the text. While I've achieved this, the issue now is that the glyphicon is not vertically centered within the badge. Whenever I attempt to add marg ...

What is the process for choosing a match and dividing a string in Ruby?

In my Ruby code, I'm trying to filter and trim an array of strings but encountering some issues along the way. Here is how my array of strings looks: 321 com.apple.storeaccountd.daemon - com.apple.cmio.AVCAssistant - com.apple.diskmanagementd 150 co ...

How can you tell if a contenteditable div is currently in focus?

Essentially, my setup consists of: HTML: <div class="div1"> <div class="as-text-box" contenteditable="true"></div> </div> CSS: .div1{ position:absolute; height:50px; width:200px; background:white; border:1px solid #c ...

Ways to guarantee that a link is deactivated upon page load

I'm facing two issues Here is the markup for the link: <a href="/Home/DisplaySpreadSheetData" id="displaySpreadSheetLink">DisplaySpreadsheetData</a> 1) I'm trying to disable the link by default under document.ready ...

VisualMap in ECharts featuring multiple lines for each series

If you'd like to view my modified ECharts option code, it can be found at this URL: Alternatively, you can also access the code on codesandbox.io : https://codesandbox.io/s/apache-echarts-demo-forked-lxns3f?file=/index.js I am aiming to color each l ...

Tips for changing the order of a child element within a parent element that is positioned above its own parent element

I have a unique setup with two parent elements, one black and one red. Each parent element contains its own child element - the black parent has a gray div child, while the red parent has a pink div child. There are some constraints to consider: I am no ...

Obtaining various values for checkboxes using dynamic data in a React application

Retrieve all checkbox values dynamically import * as React from "react"; import Checkbox from "@mui/material/Checkbox"; import FormControlLabel from "@mui/material/FormControlLabel"; import axios from "axios"; expor ...

Can the looping feature be applied to CSS?

I've been reusing the same CSS code multiple times, just changing the names each time. It feels repetitive to call the same CSS repeatedly with different names. I'm considering looping through it instead. Any suggestions? #block1{display:block; ...

Having trouble pushing to an array in Angular typescript? It seems to be returning as undefined

As a newcomer to Angular with a basic understanding of JavaScript, I am attempting to create a program that can solve Sudoku puzzles. In a 9x9 grid, there are a total of 81 points or squares. To efficiently check for violations of Sudoku rules - no repeati ...

Identifying the color category based on the color code in the props and displaying JSX output

I am in need of a solution to display colors in a table cell. The color codes are stored in mongodb along with their descriptions. I am looking for a library that can determine whether the color code provided is in RGB or hex format, and then render it acc ...

Is it a jQuery photo gallery that showcases images sourced directly from a database?

I'm feeling a bit stuck with my coding and could really use some assistance. I am currently working on implementing a jquery gallery plugin that pulls images from a database using a PHP script instead of directly from a folder on the server. <?php ...

Choose a text input form field simultaneously?

Is it possible to create a select field that also acts as an input form simultaneously? I need the options in this hybrid field to range from 0.01 to 10.00, while ensuring it always displays 2 decimal places. Curious how I can achieve this functionality ...

Locate the .offset value for every element that has the class X

Is there a way to retrieve the .offset of multiple elements using variables? I envision something along these lines: var position = $(this).offset().top; $(".number").text(position); My goal is for each element with the .number class to display its own s ...

Unable to retrieve output from jQuery function in PHP

I'm facing an issue retrieving data from the database and I can't seem to pinpoint why there's no output. My approach involves using jQuery/AJAX: $(document).ready(function(){ $('#banktransfer_blz').blur( function(){ ...

Purge IndexedDB data on tab closure

Storing data in indexedDB instead of sessionStorage is necessary due to the size exceeding 5 MB. I'm uncertain about the cleanup strategy. I want the data to persist during page reloads or navigation, but I'd like it removed if the user closes t ...