Finding the image source of a clicked image

Is it possible to retrieve the image src after clicking on another image?

$(document).ready(function() {
  $('img.getimage').click(function() {
    alert($(this).attr('src'));
  });
});
.sinistra {
  width: 150px;
}

.getimage {
  width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="content">
  <div id="mywrap">
    <img class="getimage" src="http://icons.iconarchive.com/icons/umut-pulat/tulliana-2/128/k-get-icon.png" /><br />

    <img class="sinistra" src="http://www.bicielettriche.bikeitalia.it/wp-content/uploads/2014/11/bici-elettrica-piaggio.png" />
  </div>

  <br /><br /><br />

  <div id="mywrap">
    <img class="getimage" src="http://icons.iconarchive.com/icons/umut-pulat/tulliana-2/128/k-get-icon.png" /><br />

    <img class="sinistra" src="https://eradellabicicletta.files.wordpress.com/2013/01/bici-da-corsa-rb1000-team-edition.jpg" /><br />
  </div>
</div>

If an img element with the class 'getimage' is clicked, the goal is to access the src attribute of the image within the same div identified by the ID mywrap. There should be no additional classes or divs added.

Access the fiddle

Answer №1

Take a look at this FIDDLE, I utilized fiddle to locate the sibling of img.sinistra when the getimage is clicked.

$(document).ready(function () {
        $('img.getimage').click(function () {
            alert($(this).siblings('img.sinistra').attr('src'));
        });
}); 
.sinistra {
  width: 150px;
}
.getimage {
  width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="content">
<div id="mywrap">
<img class="getimage" src="http://icons.iconarchive.com/icons/umut-pulat/tulliana-2/128/k-get-icon.png"/><br />

<img class="sinistra" src="http://www.bicielettriche.bikeitalia.it/wp-content/uploads/2014/11/bici-elettrica-piaggio.png"/>
</div>

<br /><br /><br />

<div id="mywrap">
<img class="getimage" src="http://icons.iconarchive.com/icons/umut-pulat/tulliana-2/128/k-get-icon.png"/><br />

<img class="sinistra" src="https://eradellabicicletta.files.wordpress.com/2013/01/bici-da-corsa-rb1000-team-edition.jpg"/><br />
</div>
</div>

Answer №2

To utilize closest() along with find(), ensure that each id is unique. Avoid using the same id "mywrap" for all container divs; consider assigning them a shared class instead if necessary. Currently, neither approach is required:

$('img.getimage').click(function () {
            //Locate the parent div of the clicked link
            let containerDiv = $(this).closest('div');
            let srcVal = $(containerDiv).find('.sinistra').attr('src'));
        });

Answer №3

When using jQuery, there are several methods to achieve this task. One approach is to target the parent element of the icon and then access the child image with the sinistra class.

jQuery

$(document).ready(function () {
  $('img.getimage').click(function () {
    alert($(this).parent().children('.sinistra').attr('src'));
  });
});

JSFiddle

Alternatively,

You can also directly select the sinistra sibling.

jQuery

$(document).ready(function () {
  $('img.getimage').click(function () {
    alert($(this).siblings('.sinistra').attr('src'));
  });
});

JSFiddle

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

Retrieve data from the controller of the selected element on the subsequent page using AngularJS

Currently, I am in the process of developing an ecommerce platform using angularjs. In my controller, I have a list of various products structured like this: $scope.products = [ {imgLink: 'product1.jpg', name: 'Wingtip Cognac Oxford&apo ...

A JavaScript variable... cannot access

Can anybody explain to me the reason behind this reference not functioning properly? let linkId = $(this).attr("data-id"); //retrieve the id data when a tag is clicked $(".wrapper").find("section[id=linkId]").css({"background-color": "red"}); ...

The particles.js with absolute positioning is currently overlapping my div with relative positioning

Visit this link <div class="outer-container"> <div id="particles-js"> <div class="your-content"> <article id="3" class="bg-dusk transition md:group-hover:opacity-50 md:hover:opacity-important md:hov ...

Exploring jQuery: Implementing a SlideDown Effect on Loading Questions

Greetings, this is my debut post on stackoverflow. I have been an avid reader and learner here. I am currently using a jQuery function to load posts in WordPress themes using the .load function. However, I am facing a challenge that I cannot resolve on m ...

CSS code to modify background color upon mouse hover

I am currently working on creating a navigation menu. Check out the code snippet here: http://jsfiddle.net/genxcoders/ZLh3F/ /* Menu */ .menu { height: 100px; float: right; z-index: 100; } .menu ...

Include the button beneath the Rating section using JQuery or AJAX

I am having trouble adding buttons after the result.date in my code. Placing the buttons between td tags is causing an [object Object] error to show up. $.ajax({ type: 'GET', url: 'someUrl.php', data: {op : "demo"}, da ...

Automatic scrolling feature in JavaFX

I am currently working on developing a chat box using JavaFX. My goal is to implement an auto-scroll feature that will scroll down the page when it gets filled up. However, I am facing some issues with this functionality. import javafx.application.Applica ...

jQuery AJAX calls are unsuccessful, while NodeJS requests are running smoothly

I am experiencing an issue with a RESTful web service that returns JSON. Interestingly, a NodeJS command line test application is able to retrieve the JSON data without any problems: Successful NodeJS Application: var request = require("request"); var bt ...

The find function within $(this) is malfunctioning

I'm having issues with displaying/hiding content when clicking on a table row. Here is the simplified code snippet: HTML: <table> <tr onclick="showDetails()"> <td>Some text <br> <span class="hiddenC ...

Clicking on Google Code Prettify does not trigger syntax highlighting

I utilize Google Code Prettify for syntax highlighting my code. Below is the HTML snippet I use: <head> <script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script> </head> <body> ...

Guide on creating a logarithmic-based bar rating system

I am working on creating a bar rating system for my website, but the current design doesn't look great. I want the height of the bars to increase like an exponential curve gradually, starting off not too steep and gradually increasing afterward. Here ...

Velocity 1.5 causing issues with jQuery compatibility

I am encountering issues with incorporating jQuery into my code within a velocity template. Despite using velocity 1.5, the jQuery functionality does not seem to be working properly. Could you please suggest a solution? <script src="/CostTrackerReport ...

Is it possible to prevent a webpage from being refreshed?

I need help with an HTML page that puts the worker on pause time which will be subtracted from his/her day job. The issue is that when he/she refreshes the page, the timer starts from the beginning automatically. I want it to continue without resetting. Is ...

Keep some table columns locked in place on your webpage while others are located off-screen, requiring a scroll to access

I have a question regarding an HTML table. There is a windows application that features a vertical scrollable table where some columns are fixed on the page while others remain outside the page. Here is an example: The black border represents the responsi ...

The inclusion of the <div> tag disrupts the functionality of the Material UI Grid

While attempting to enclose my element within a <div> that is nested inside the <Grid>, I realized that this was causing the <Grid> layout to break! Surprisingly, when I tried the same approach with Bootstrap grid system, this issue did n ...

Issues with tabbed navigation functionality in jQuery

I'm encountering some difficulties with the tabbed navigation I created using CSS. Essentially, when a button is clicked, it should remove the hidden class from one div and add it to the other. However, what actually happens is that the div which sho ...

What is causing my background div to jerk around when I implement jQuery animate to adjust its height?

UPDATE: I have replicated my issue in jsFiddle: http://jsfiddle.net/leongaban/3v8vW/3/ I am dealing with 2 tabs - one should reduce the height of the form-background when clicked, while the other should increase it. I want a smooth animation without any a ...

Having trouble with the width of the Material-UI drawer feature

Encountering an issue with the material-ui drawer. I adjusted the width of the drawer container, which led to a problem where the drawer remains slightly inside the page and visible without clicking the button. It seems to be related to the transform attri ...

What is the best method for showcasing two images side by side in a column layout?

I need to showcase 2 images in a row using AngularJS, with the next two images in the following row and so forth. Img1 Img2 Img3 Img4 This is my code: <section id="content"> <div class="content-wrap"> <div class="container clearfix "& ...

Instructions for sending a server error response with php

When the user clicks on the delete button, my jQuery script sends a request to the server to delete the selected item. Now, I want my php script to return either a success or an error response. Is it possible to trigger the error callback if the item can ...