How to rename a class of an image tag using jQuery

I need to update the class name in my image tag

<img src="img/nex2.jpeg" class="name">

When hovering over with jquery, I want to add a new class to it. After hovering, the tag should appear as follows:

<img src="img/nex2.jpeg" class="name secondname">

Upon removal of hover, it should revert back to:

<img src="img/nex2.jpeg" class="name">

Answer №1

Here's the solution you've been searching for:

jQuery(function($) {
    $('img.name').hover(function() {
        $(this).addClass('secondname');
    },
    function() {
        $(this).removeClass('secondname');
    });
});

Alternatively, you can utilize CSS for even better results:

img.name:hover {
   // Add your custom styles here
}

Answer №2

$("img").hover(
  function() {
    $( this ).toggleClass('highlight');
  }, function() {
    $( this ).toggleClass('highlight');
  }
);
.highlight {
  border: 3px solid blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="http://lorempicsum.com/futurama/200/200/2" class="avatar">

Answer №3

Answer:

Here is a JavaScript code snippet that allows you to apply styling dynamically without the need for jQuery:
This approach grants you flexibility in styling elements using JavaScript, and it is also more efficient than using jQuery.

    <script type="text/javascript">
        function addClass()
        {
          document.getElementById("apple").className += " secondname";
        }
function removeClass()
        {
        //replaces all classes with initial class
          document.getElementById("apple").className = "name";
        }

        window.onload = function()
        {
            document.getElementById("apple").addEventListener( 'mouseover' , addClass );
            document.getElementById("apple").addEventListener( 'mouseout' , removeClass );
        }
    </script>
    ...
    <img src="img/nex2.jpeg" id="apple" class="name">


It's important to note that utilizing CSS remains the most efficient method:

img.name:hover
{
//apply all styles from class name secondname
}


By following this technique, you can streamline your styling process by using just one class instead of two.
Feel free to explore different styling options according to your preference.

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

Issue with state change in Component (React with Redux)

I am another person facing a similar issue. I have been unable to identify the error in my code yet. I suspect it has something to do with mutation, but despite trying almost everything, I am at a loss. My component does not update when I add new items to ...

"Implementing drag and drop functionality in Vue.js without the need for a

Exploring html 5 drag and drop functionality using vue js has been a challenging experience for me. After following the w3schools tutorial on drag and drop, I managed to get it working in a basic html file but faced difficulties when implementing it in my ...

What is the best way in jQuery to pass an event to a parent anchor if necessary?

I'm working on a project in ClojureScript using jQuery, and I believe the answer should be applicable to both ClojureScript and JavaScript. My issue involves a helper function that creates an anchor element and then places an icon element inside it. ...

Having trouble with Jquery's Scroll to Div feature?

When I click on the image (class = 'scrollTo'), I want the page to scroll down to the next div (second-container). I've tried searching for a solution but nothing seems to work. Whenever I click, the page just refreshes. Any help would be gr ...

Python's Selenium execute script does not support setTimeout function

Hey there! I was attempting to pause the Selenium execution for a few seconds in order to wait for a Modal popup to appear. Unfortunately, using time.sleep(5) did not work with PhantomJS (apparently, PhantomJS does not support sleep function). So, I decide ...

Is there a way to showcase an epub format book using only HTML5, CSS, and jQuery?

Can ePub format books be displayed in a web browser using only HTML5, CSS, and jQuery? I would appreciate any suggestions on how to accomplish this. Additionally, it needs to be responsive so that it can work on iPad. While I am aware of this requirement, ...

Tips for efficiently resolving and compiling a bug within an NPM package, ensuring it is accessible to the build server

This question may seem a bit unconventional. I am currently using an npm package that includes built-in type definitions for TypeScript. However, I have discovered a bug in these definitions that I am able to easily fix. My goal is to make this updated ve ...

Build a stopwatch that malfunctions and goes haywire

I am currently using a stopwatch that functions well, but I have encountered an issue with the timer. After 60 seconds, I need the timer to reset to zero seconds and advance to one minute. Similarly, for every 60 seconds that pass, the minutes should chang ...

Learning how to replace the alert function with Bootbox

I am currently working on a form that posts to a MySQL database. I want to replace the alert function triggered by the Malsup jQuery Form Plugin with the one created by the Bootbox plugin. Even though both plugins are functional, I struggle to integrate th ...

Using jQuery to Retrieve Accurate User Identification - Making AJAX Requests

Currently, I am facing a bit of a dilemma. I have implemented 2 jQuery scripts to handle updating a simple database row based on user ID and session. This functionality allows users to send a "Gift" that adds value to their database row column "bonus". Wh ...

Total Output Calculation

In my latest coding project, I have crafted a unique algorithm to calculate exam scores with the inclusion of interactive buttons! function incorrectResponse() { var calc = 0; var calc2 = 1; var divElement = document.createElement("div"); divEle ...

Animation not functioning properly after Ajax call in event onload

After making an AJAX call to load all the data, I encountered an error in the response data. The code snippet likeObj('#like'+postid).effect("bounce", {times:1,distance:25},400); throws an error stating that likeObj is not a function. I'm s ...

Guarantee: exclude all successful and unsuccessful responses and only carry out the .finally method

I have a function named request: function request (endpoint) { return axios.request(endpoint).then(api.onSuccess).catch(api.onError) } api.onSuccess: onSuccess (response) { let breakChain = false ... adding some logic here ... return break ...

How about showcasing bigger images in the main body of the page?

When it comes to using CSS sprites for images, the typical advice is to reserve it for smaller images like icons. Why should larger content images only be represented through <img> elements? Are there not benefits to utilizing spriting for all types ...

One way to achieve the same functionality as onclick in an Ajax call using

I have two JSPs. In the first JSP, I am making an ajax call and receiving data (Ajax body) from the second JSP. However, I am unsure of how to execute jQuery when an argument is present in the function. Everything works fine without an argument. In the ...

executeScript - run when dialog is confirmed

One issue I am facing involves a script that runs smoothly when loaded using the traditional standalone method: <Script src="wthvideo/wthvideo.js"></script> However, things don't go as planned when trying to load it using the Ajax/getScr ...

Having issues with the crucial npm installation of @babel/plugin-transform-react-jsx

Apologies for the inconvenience, but this is my first post. I encountered an issue during npm start, and received this error message: /Users/hp/Desktop/Wszystkie Projekty/ravenous/src/components/BusinessList/BusinessList.js SyntaxError: C:\Users\ ...

What is the best way to send a form value to a servlet?

As someone who is relatively new to programming, I kindly ask for your patience with me. I am currently attempting to extract values from a form (embedded in a JSP) using JavaScript, and then make a post request to a servlet. The form consists of 6 differ ...

Error in HTML5 video: Unable to access property '0' as it is undefined

I am trying to create a simple block displaying an HTML5 video tag. I want the ability to play different videos along with their titles from a JSON file by using previous and next buttons. Clicking the next button should play the next video, and the same g ...

Is it possible to delete browsing history in Express using node.js?

Upon user login, I store user information in browser sessions on the client side (using Angular) like this: $window.sessionStorage.setItem('loggedInUser', JSON.stringify(val)); For logout authentication on the backend (using Passportjs), I have ...