Retrieve the Nth class of an element that has multiple classes without relying on the .attr("class") method in jQuery

Within a container with two styles, the initial nested div

<div class="datacheck">
   <div class="classic_div_data customdataid_305">
     some values are included here
   </div>
   <div class="optiondiv">
   </div>
</div>

I am looking to extract a substring (in this case the number 305) from the second style (customdataid_305) of the first inner div. To accomplish this, I require access to the classes.

I managed to achieve this using jQuery

var xyz= $($(".datacheck").find("div")[0]).attr("class").split(" ")[1]

which allows me to retrieve the class.

Is there a more straightforward method for accomplishing this? I am hoping for something similar to $(element).class() that potentially returns an array of classes

Answer №1

When it comes to obtaining an array of classes, there isn't a direct method available, although the native DOM classList can be somewhat similar. However, relying solely on classList may not necessarily simplify things.

One approach could be:

var xyz = $(".datacheck .classic_div_data").attr("class").match(/\bcustomdataid_(\d+)\b);
xyz = xyz && xyz[1];

This regex efficiently captures the numeric part of the class without being overly sensitive (e.g., to the order of classes within the list).

For instance:

var xyz = $(".datacheck .classic_div_data").attr("class").match(/\bcustomdataid_(\d+)\b/);
xyz = xyz && xyz[1];
console.log("xyz = '" + xyz + "'");
<div class="datacheck">
   <div class="classic_div_data customdataid_305">
     some values appear here
   </div>
   <div class="optiondiv">
   </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


If modifying the HTML is an option, using a data-* attribute instead of a class might be more suitable:

<div class="classic_div_data" data-custom-id="305">

Subsequently:

var xyz = $(".datacheck [data-custom-id]").attr("data-custom-id");

Example:

var xyz = $(".datacheck [data-custom-id]").attr("data-custom-id"); 
console.log("xyz = '" + xyz + "'");
<div class="datacheck">
   <div class="classic_div_data" data-custom-id="305">
     some values come here
   </div>
   <div class="optiondiv">
   </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Answer №2

One issue you may encounter with your current design is the risk of breaking logic if the order of classes changes or a new class is added. Additionally, converting a DOMElement from a jQuery object back into a jQuery object can be inefficient.

A more effective approach would be to utilize data-* attributes for storing custom data, as demonstrated below:

$('.classic_div_data').click(function() {
  console.log($(this).data('customdataid'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="datacheck">
  <div class="classic_div_data" data-customdataid="305">
    some values come here
  </div>
  <div class="optiondiv"></div>
</div>
<div class="datacheck">
  <div class="classic_div_data" data-customdataid="205">
    some more values come here
  </div>
  <div class="optiondiv"></div>
</div>

Answer №3

Accessing the nth class within an element's classList is straightforward with the following code snippet:

var elem = $(".datacheck").find("div").get(0);
var nthClass = elem.classList[1];
var result = nthClass.replace("customdataid_", "");
console.log(result); //305

Answer №4

If you're looking to extract the last digit from a class, you can utilize regular expressions with the .match() method in JavaScript.

var digit = $(".datacheck > :first").attr("class").match(/[\d]+$/g)[0];
console.log(digit);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="datacheck">
    <div class="classic_div_data customdataid_305">some values come here</div>
    <div class="optiondiv"></div>
</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

When attempting to use Ajax, the operation fails; however, if I directly access the URL,

When using firebug, I attempted to make the following AJAX call: var rootUrl = 'http://172.24.105.22:8080/geoserver/Chennai_Sub/ows'; var defaultParameters = { service: 'WFS', version: '1.0.0', request: 'Get ...

angular primeng table has a checkbox to select all checkboxes

Is there a way to check all checkboxes in a table when the checkbox in the table header is clicked? I am currently utilizing angular 12 and primeNG table for this functionality. <p-table styleClass="text-sm" [value]="value" [loading] ...

The information was not displayed in the message exchange

I'm currently working on a project involving a google chrome extension where the content.js script sends a message to popup.js. I'm also attempting to take some text from content.js and display it in popup.js. Here is my entire code: Here's ...

IE8 is encountering a null JSON response from the HTTP handler, unlike IE10 and Chrome which are not experiencing this

Here is my JavaScript code snippet: patients.prototype.GetPatient = function(patient_id,callback) { var xmlhttp; var fullpath; try { if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { ...

Choosing a single radio button value within a nested ng-repeat loop in AngularJS

Help needed with selecting only one radio button value in nested ng-repeat. Please review the source code and suggest any potential mistakes. <form ng-submit="save()"> <div ng-repeat="x in surveyLst"> <div class="row"> < ...

Building a class structure with a JavaScript MVC approach - best practices

I am looking to develop a JavaScript web application using the MVC-like principle. While my code is functional, I am facing challenges in implementing it correctly. I have created a global variable called APP where I store controllers, views, and other com ...

Tips for updating the left positioning of a Div element on the fly

Although my title may not fully explain my goal, I am dealing with dynamically created div elements. When a user triggers an ajax request to delete one of the divs, I want to remove it from the DOM upon success. The issue arises in adjusting the layout aft ...

The operation is unable to be executed in an external document

Working on a WordPress page, I am utilizing the Google Maps API. The functions in my file are as follows: function custom_map_style() { // Enqueue Google Maps API wp_enqueue_script('maps', 'https://maps.googleapis.com/maps/api/js? ...

The height of the ReactPlayer dynamically adjusts to accommodate content beyond the boundaries of the page

I have a video on my webpage that I want to take up the entire screen, but currently, users have to scroll a bit to reach the bottom, which is not ideal. This is my JavaScript: <div id="page"> <div id="video-container"> ...

simulating interaction with databases within API routes

I am currently working on developing a full stack application using NextJS along with a MySQL database. Within my API routes, I interact with this database by making calls to various functions such as createOne(), which is responsible for creating new inst ...

An error occurs in TypeScript when attempting to reduce a loop on an array

My array consists of objects structured like this type AnyType = { name: 'A' | 'B' | 'C'; isAny:boolean; }; const myArray :AnyType[] =[ {name:'A',isAny:true}, {name:'B',isAny:false}, ] I am trying ...

The unique text: "User-defined input element disregards changes initiated through

I created a custom input component that functions correctly, but I have encountered an issue. When I attempt to update the value through a method, the model gets updated but the input value remains unchanged. Here is my component: https://codepen.io/ken-r ...

The inline feature of the Bootstrap input group addon is not being utilized

Check out my code snippet here: http://www.bootply.com/iR1SvOyEGH <form> <div class="form-group"> <label for="inputEmail">Company Name</label> <input type="text" class="form-control"> <span class="input-gro ...

Executing a child component function once the parent component data is loaded in Angular 5

In my project, I have a parent component called program-page.component where I am invoking a function to fetch some data. ngOnInit() { this.getProgress(); } getFirstProgramItem() { this._contentfulService.getProgramItem(4, 1) .then((programItem) = ...

Retrieving an Element that Triggered an HTTP GET Request in Node.js with Express

In my Express front-end development project, I have a table with rows containing links that trigger GET requests. These requests are sent to the back-end, which is created using node.js, in order to retrieve files corresponding to each row. All links follo ...

Is there a way to prevent Express from automatically adding a slash to a route?

Despite my extensive search for a solution, none of them have proven effective. Perhaps you could provide some assistance. I'm currently working on a Node.JS and Express-based plugin webserver. The main code for the webserver is as follows: This sec ...

Unable to assign an ID to an element in JavaScript, as it will constantly be undefined

Is there a way to automatically generate unique IDs for jQuery objects if they don't already have one? I need these IDs for future requests. I wrote the following code, but it doesn't seem to be working. The ID's are not getting set and the ...

Angular - the offspring of another element

I'm currently exploring the possibilities of identifying if a clicked element is a child of another using Angular. In jQuery, I would typically use has() for this task, but I'm unsure of the equivalent method in Angular aside from iterating throu ...

Issue with ng-bind-html in TranslateJS causing problems

I have been working on implementing translation in a web application using angularJS and the angular-translate repository, which can be found at . As per the documentation, it is possible to use this repository to set text for a specific element in the HTM ...

I'm having trouble getting my modal to work and display properly; I need to send it to the code behind for further assistance

I'm having trouble with my modal. I'm trying to create a sign-up modal and send it to my code behind page. I've incorporated bootstrap lumen and jquery, but I could use some assistance. Any help would be greatly appreciated. Thank you in adv ...