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

Trigger the callback function once the datatables DOM element has finished loading entirely

Hello there! I have a question regarding datatables. Is there any callback function available that is triggered after the datatables DOM element has finished loading? I am aware of the callbacks fnInitComplete, but they do not serve my purpose. Specificall ...

Angular 2: Enhancing Tables

I am looking to create a custom table using Angular 2. Here is the desired layout of the table: I have a Component that provides me with data export class ResultsComponent implements OnInit { public items: any; ngOnInit() { this.items = [&apos ...

Struggling to modify a document in a MongoDB collection with an HTTP Put request?

I've recently started working with AngularJS and I encountered an issue while trying to update my MongoDB Database. I'm facing a problem when attempting to update an object within my collection. The code snippet below showcases my approach: //li ...

Issue with accessing Contacts API functionality in Firefox OS application

I have followed all the instructions provided in this documentation, but I keep encountering errors. My testing environment is the "Firefox OS 2.2" simulator. In my manifest file, I have included two permissions as follows: "permissions": { "deskto ...

I need to update the class definition of a navigation menu item that contains an "a" tag with the class "section-link". How can I dynamically add the class "popover-link-a" to this definition using JavaScript?

If the grid in the body contains no data, then I want to display a pop-up message on the menu li element. This pop-up is triggered by adding the class popover-link-a. The current setup looks like this: <li id="tecrube" runat="server" ...

How can I effectively assign model data to a service property in an AngularJS controller?

I have established a service to facilitate the sharing of data/state across multiple controllers. One of the controllers updates certain properties within the service using scope data through a save function. The updated data is then accessed by other cont ...

Switching the background image of a div when hovering over a particular list item

Here is my HTML: <li><a href=""><div class="arrow"></div>List Item</a></li> I'm looking to change the background image of the "arrow" class when hovering over the "List Item" with a mouse. The "arrow" class repres ...

Reinitializing AngularJS form controls

Check out this codepen example: http://codepen.io/anon/pen/EjKqbW I'm trying to reset the form elements when the user clicks on "Reset". The div elements f1,f2,f3 should be hidden and the searchText box cleared. However, the reset button is not trig ...

Using JQuery to implement a date and time picker requires setting the default time based on the server's PHP settings

I have implemented a jQuery UI datetime picker in my project. As JavaScript runs on the client side, it collects date and time information from the user's machine. Below is the code snippet I am currently using: <script> // Function to set ...

Unable to retrieve the initial return value from the function that has been promisified

Previously, the code functioned correctly but was not properly promisified. const express = require('express'); function runServerAndReturn() { app = express(); console.log('Before starting server'); const server = app.lis ...

Issue with $watch in Angular Modal not triggering

Having trouble using $watch with a radio button located inside an AngularJS Modal. The $watch doesn't seem to work when the value changes within the modal. If I move the radio buttons outside the modal, the $watch functions as expected. You can see ...

Adding a Click class can cause significant disruption to the entire CSS layout

I am facing an issue with transforming the X position and appending an additional class to create a slide effect in React. It seems to be working differently compared to using vanilla JavaScript. Below is the code snippet: .inputModal { position: absolut ...

The pre-save function in Mongoose does not seem to be working properly when using discrimin

I am facing an issue where the pre save hook is not being called before saving the owner in mongoose. Is there a workaround for this problem? const baseOptions = { discriminatorKey: '__type', collection: 'users' } const Base = ...

Using jQuery Ajax to Send Values Between Functions and Replace Nulls

I need assistance with handling the value from a dropdownlist in my JavaScript function. The function works well if the value is not Null, but I want to replace a Null value with the static value "asc" before passing it to the next function. function g ...

Using React Hooks to render radio buttons within a map iteration

My code contains a nested map function where I try to retrieve values from radio buttons. However, the issue is that it selects all radio buttons in a row instead of just one. Below is the snippet of my code: <TableHead> <TableRow> ...

Using JavaScript (AJAX), learn the process of incorporating XML data within HTML files

I'm relatively new to HTML and I'm attempting to create a self-contained HTML page that includes all necessary CSS, data, and JavaScript within the file itself. While I understand that this will result in a rather messy HTML document, it is essen ...

The task of mapping an array of objects with nested values using JavaScript is proving to

Attempting to convert an array of objects with nested values in child objects like: const objs = [{ "B": { "value": 1, }, "D": { "value": "45" }, "E": { "value": "234" }, ...

Creating adaptable breakpoints for content using Bootstrap or pure CSS

I'm trying to create a responsive layout using the Bootstrap "row" and "col" classes, but I'm having trouble figuring out how to structure the content. Here's what I mean: https://i.sstatic.net/WkMmE.png This is my current HTML structure: ...

Conduct a unit test to verify that a function successfully connects to an API and accurately stores the retrieved data in a variable

Currently, I am working on creating a unit test for my writing and JavaScript code. This area is still challenging for me, so I am in the process of learning how to do it correctly. The specific function I am focusing on makes an API call and then assigns ...

React error: The module "react-router-dom" does not have a member named "useNavigate" available for export

I'm attempting to include useNavigate for use as outlined in the top answer here: react button onClick redirect page import { useNavigate } from "react-router-dom"; However, I am encountering this error: export 'useNavigate' (impo ...