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

Substitute the <body> tag with a different tag

I am attempting to use the following code to replace the <body> tag on a page with <body id="khanqah"> echo str_replace("%body%", "khanqah", "<body id='%body%'>"); Although it adds <body id="khanqah"> to the page, the or ...

The frozen column feature of jQGrid does not function properly when it is implemented inside a jQuery Tab container

I have encountered an issue with my jQuery TAB setup. In the first tab, I have a jqGrid with frozen columns which is functioning correctly. However, in the second tab, another jQgrid with frozen columns is not working as expected. Upon removing the code t ...

Neither req.body nor req.file contain any data

Hey everyone, I'm new to coding and currently working on creating a basic markdown blog. However, I'm facing an issue where req.body doesn't contain my markdown field and req.file is undefined when trying to upload an article. I'm unsur ...

The content within the iframe is not displayed

I've set up a dropdown menu with separate iframes for each option. Here's the code I used: $(function(){ $('#klanten-lijst').on('change',function(){ $('#klanten div').hide(); $('.klant-'+t ...

Create a new button dynamically within an HTML table row using pure JavaScript programming techniques

Currently, I am retrieving JSON data from an API and then displaying this data in an HTML table using plain JavaScript. My goal is to dynamically add a button at the end of each row for additional functionality, but so far, I have been unable to figure out ...

The checkbox event listener becomes dysfunctional when the innerHTML of its container is modified

My current challenge involves creating checkboxes with a blank line inserted after each one. I also need these checkboxes to trigger a function when changed. This is my code snippet: var div = document.getElementById("test"); var cb1 = document.createEl ...

Show Pop in relation to modified Text

When the user clicks on the text, a pop-up is displayed after the last word in the text.... https://i.stack.imgur.com/VWQCa.png The logic being used is : left = layer.width + layer.x Code : document.getElementById(lightId).style.left = layer.x + docume ...

What is the best way to deduct pixels from numbers using JavaScript?

Currently, I am attempting to adjust the height of the footer based on the height of another div element. My approach involves utilizing the .css("height") function. However, I am encountering difficulty as the function does not seem to return the value i ...

Using the jQuery before() method to manipulate form fields

Is it possible to utilize the jQuery before method to insert a form? An example scenario could be as shown below: <script> $(document).ready(function() { $("button").click(function() { $("button").before('<form><input type="text ...

Enhancing HTML table interactivity: Updating class of cells upon hover

While attempting to update the class on hover, I noticed that the class changes from 1 to hovering cells However, I want the class to change from 1 to currently hovered cells If moving the mouse from 1 to 10 and then to 2, the currently hovered cells wil ...

Having difficulty implementing dynamic contentEditable for inline editing in Angular 2+

Here I am facing an issue. Below is my JSON data: data = [{ 'id':1,'name': 'mr.x', },{ 'id':2,'name': 'mr.y', },{ 'id':3,'name': 'mr.z', },{ & ...

Utilizing Sequelize with Typescript for referential integrity constraints

After defining these two Sequelize models: export class Users extends Model<Users> { @HasMany(() => UserRoles) @Column({ primaryKey: true, allowNull: false, unique: true }) UserId: string; @Column({ allowNull: false, unique: tru ...

The process of matching the full names of the source and destination Strings in Node.js

Need assistance comparing two strings with a third string in a JSON Array for full names var source = intentObj.slots.toPlazaName.value.toString(); // Jaipur var destination = intentObj.slots.fromPlazaName.value.toString(); // Kishangarh Compare with t ...

What is the optimal method for delivering HTML content in a Node.js application using Express.js?

My current approach involves serving all HTML content directly from my app.js/server.js file, as shown below: app.get('/', function(req, res) { res.render('index.html'); }); app.get('/about', function(req, res) { res. ...

Tips for resolving a 403 error and SSH connection issue on an Azure Web Service website

Recently, my web app created on Azure using Express and Node 18 worked perfectly during development locally. However, when I attempted to host it on an Azure web app, I encountered issues. The site failed to display anything and a 403 error was returned in ...

Arranging xCharts based on the weekday order

Struggling with xCharts, specifically trying to display a bar chart showing numbers with corresponding days of the week in order. Despite my efforts, I can't seem to get them to appear in the correct sequence. Refer to the image below for reference: ...

Unable to import necessary modules within my React TypeScript project

I am currently building a React/Express application with TypeScript. While I'm not very familiar with it, I've decided to use it to expand my knowledge. However, I've encountered an issue when trying to import one component into another comp ...

Tips for modifying a request api through a select form in a REACT application

Apologies if this question seems a bit basic, but I need some help. I am working on creating a film catalog using The Movie Database API. I have successfully developed the home and search system, but now I am struggling to implement a way to filter the fi ...

Use custom styles or CSS for the file input element: <input type="file">

Can CSS be used to achieve consistent styling for <input type="file"> in all browsers? ...

Can someone share tips on creating a stylish vertical-loading progress bar with a circular design?

Currently, I am working on developing a unique progress bar that resembles a glass orb filling up with liquid. However, due to its rounded shape, the traditional approach of adjusting the height does not produce the desired result (as illustrated in this f ...