Guidelines for retrieving a class name using jQuery when hovering over a div

I need assistance in fetching the class name by hovering over a div. Both divs have the same id but slightly different class names. Here is an example:

<div id="1-someid" class="1-example-class border cz">
...more elements go here....
</div>

and

<div id="2-someid" class="2-example-class border cz">
...more elements go here....
</div>

Update: I've updated the id names to be unique as suggested by experts below. :) Thank you for all the help.

Now, what I am looking for is that when a user hovers over the div with 1-example-class, it should return the class name 1-example-class. Similarly, when someone hovers over the div with 2-example-class, it should return the name 2-example-class.

This way, I can use parseInt() on the name to retrieve the number 1, 2, 3, and so on.

It's important to note that writing a static script for just 1-example-class or 2-example-class won't suffice as there are many more divs like this with different numbers attached to them.

Can anyone assist me with this? I tried the following code snippet but it didn't work:

$('#someid').hover(function() {
        var class_names = $(this).attr('class');

        var class_name = class_names.split( ' ' ); 

        var c = parseInt( class_name[0] );

        console.log( c );
});

Your help would be greatly appreciated.

Answer №1

To find the desired elements, using an attribute selector and Regex is the most effective method:

$("[class*=example-class]").hover(function() {
    var c = this.className.match(/(\d+)-example-class/)[1];
    console.log(c);
});
  • $("[class*=example-class]") targets elements with a class attribute containing 'example-class' string.

  • this.className.match(/(\d+)-example-class/)[1]
    extracts the associated number from the class name.

Answer №2

If you're looking for a solution based on your current setup, here's one that might help:

$('div').hover(function() {
        // grab the class attribute and split it by spaces
        var class_names = $(this).attr('class').split( ' ' );

        // iterate through each class
        $.each( class_names, function( k,v ){
            // check if this class matches the example you provided
            if ( v.indexOf("example-class") > 0 ){
                // if it does, remove the text part of the class name
                var this_num = v.replace( '-example-class', '' );
                // output only the numeric value to the console
                console.log( parseInt( this_num ) );
            }
        });

});

This approach allows flexibility in class configuration, meaning the order of classes doesn't matter as long as it contains the specified string. It no longer relies on the first listed class being the example string class.

For an illustration, check out this example: https://jsfiddle.net/31505tw1/

In the demo, I've replaced duplicate IDs with classes since HTML standards dictate that each ID must be unique.

Answer №3

There are various methods to achieve this, however, it has been pointed out by other users that the issue lies in using the same ID multiple times. This is the primary reason why your current code is not functioning properly. By selecting one of the different shared classes as your selector, your original script should work as intended:

$('.border').hover(function() {
    var class_names = $(this).attr('class');

    var class_name = class_names.split( ' ' ); 

    var c = parseInt( class_name[0] );

    console.log( c );
});

Answer №4

Start by giving each div a unique ID: https://example.com/uniqueID

This not only ensures valid HTML, but also allows your jQuery script to differentiate between the different elements. Once you have assigned unique IDs, you can target each div individually and continue with the rest of your code.

<div id="firstDiv" class="example-class border cz">
...more content here....
</div>

<div id="secondDiv" class="example-class border cz">
...more content here....
</div>

https://jsfiddle.net/05r8f013/1

Answer №5

It is important for ID's to be unique throughout an HTML document. If you are using the classname to retrieve data, consider adding a name field to the div:

<div name="someid" class="1-example-class border cz">
...additional elements here....
</div>

<div name="someid" class="2-example-class border cz">
...additional elements here....
</div>

 $('[name="someid"]').hover(function() {
    var class_names = $(this).attr('class');
    var class_name = class_names.split( ' ' ); 
    var c = parseInt( class_name[0] );
    console.log( c );
 });

Answer №6

One option might be to try this approach:

$('div').on('mouseover', function(){
if ( $(this).hasClass('some class') ) {
//Perform certain action
} else {
//Perform a different action...
}

Answer №7

To target the hovered elements that have a specific class name pattern, you can use a regular expression (Regex) in your script:

<div id="someid" class="1-example-class border cz">
...content of the element...
</div>

<script>
$('#someid').hover(function() {
   var className = this.className.match(/(\d)-example-class/);

   if(className){
      console.log(className[0]) // Output: 1-example-class
      console.log(className[1]) // Output: 1
   }
});

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

Creating an alert pop-up that displays text based on the prompt input type: A step-by-step guide

I'm a new to Javascript and I'm trying out some basic scripts. My objective is to display a prompt message (1.) asking for a name, then show an alert (2.) based on the input from the prompt. If the input is a valid name (a string), then the alert ...

Tips for relocating anchor elements to less desirable locations

My website has an issue with anchor elements appearing too frequently and not in the desired location. I need someone to help fix this so there are only two anchors displayed. After checking my code, it seems like there are not more than the specified num ...

Issue with jquery selector function when handling ajax response containing HTML data

Within my jquery code, I have implemented an ajax get function to retrieve the html code of a specific page. My objective is to extract a particular element from this html content. However, when attempting to do so, jquery throws the following error: SCRI ...

"Maximizing battery life: Efficient video playback on iOS in low power

Summary: I am currently working on a website that features a video set as the background which autoplays. However, I have encountered an issue on iOS devices when "Low Power Mode" is activated - the video fails to play and instead displays a large "Play" i ...

Is there a way to enable autofill functionality if an email already exists in the database or API within Angular 12?

In order to auto-fill all required input fields if the email already exists in the database, I am looking for a way to implement this feature using API in Angular. Any guidance or suggestions on how to achieve this would be greatly appreciated. ...

The controller in Angular uses the $scope symbol _

App.controller('todoController', function ($scope) { // create a message to display in our view $scope.todos = [{ name: 'angular', done: false }]; $scope.clearTodo = function () { $scope.todos = _.filter($scope.tod ...

React Login Redirect

I am struggling to implement a redirect in my React project login. Despite researching online and finding solutions using routers, I have been unsuccessful in adding it to my code correctly. Here is my code - how can I effectively implement the router? Ap ...

What is the significance of the exclamation point before and after in JavaScript?

Currently collaborating on a project and attempting to decipher the significance of the exclamation marks both before and after. import ICHING from '!json!constants/iching_deoxy.json'; ...

constructing a nested container using XMLHttpRequest

I am working on creating a nested div-container structure using AJAX and adding the text "Hello World" to the inner container. The outer container serves as a holder for the inner container in this case. Below is the code I have written: index.html: ...

What is the process behind managing today's Google image of the day?

After coming across the javascript picture control on the Google search page, I became interested in replicating it myself. The feature zooms in on a picture when hovering over it, but I couldn't locate the HTML code they were using for it. Is there ...

Why is JSP compilation essential in achieving its goals?

At the moment, I am involved in modifying JSP and subsequently uploading it to the server for compilation. Upon compilation, a .class file is generated for the modified JSP. If I were to remove the original JSP from the server, would it still function pr ...

Unable to close modal after receiving ajax response

Utilizing mdbootstrap for my current project has been a great experience. One area that I am struggling with is implementing an AJAX call upon checking a checkbox, where I expect a response from PHP indicating success (1) or failure (0). However, despite d ...

The browser has surpassed the maximum call stack size while trying to refresh with socket.io, causing an error

I've encountered an issue with my Node js server crashing whenever I refresh the browser. The websocket connection works fine initially, but upon refreshing, the server crashes with the following error: E:\Back\node_modules\socket.io-pa ...

Dynamic Bodymovin motion graphics

I'm trying to figure out the best way to embed a bodymovin exported file on my website so that it is responsive, maintains the correct aspect ratio of the logo and fonts, and fits within the borders of the site. Does anyone have any suggestions? Appr ...

I'm interested in learning about the most efficient practices for handling JSON, performing math operations, and utilizing loops in JS/React. What techniques

Short version: I'm working with a large array of JSON objects (60K+ elements) in my application I need to perform various mathematical operations such as comparison and addition Currently, I am handling this through multiple for loops (simplified ...

The Angular checked functionality is not working as expected due to the presence of ngModel

Just getting started with Angular here. I’m working on a checkbox table that compares to another table and automatically checks if it exists. The functionality is all good, but as soon as I add ngModel to save the changes, the initial check seems to be ...

Is it Possible to Achieve Callbacks From AJAX to PHP Despite the Inability to Serialize Closures?

Question How can I incorporate a PHP callback passed via AJAX, where the callback is executed by the page requested through AJAX? The Scenario Comments are submitted through AJAX with parameters serialized and encrypted for security. The issue arises wh ...

Hybrid component that combines static and dynamic elements in Gatsby

The inconsistency in behavior between the site generated by gatsby develop and gatsby build is causing an issue where the site works during development but not when it's in production. An overview of my website: My website is a simple blog-like plat ...

Optimizing HTML5 metatags and styles for a mobile application

As a C++ developer who has recently delved into using HTML5 for my mobile applications, I am in need of guidance when it comes to fine-tuning my meta tags. While I do have some knowledge in web programming, there are still gaps in my understanding. I am s ...

Typescript Tooltip for eCharts

I'm working on customizing the tooltip in eChart v5.0.2 using Typescript, but I'm encountering an error related to the formatter that I can't seem to resolve. The error message regarding the function keyword is as follows: Type '(param ...