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

Do CSS Modules consistently generate the same class name for a specific CSS class defined within the module?

I have defined the following classes in my CSS module: .container-styles { height: 20px; width: 90%; background-color: rgb(128 , 128 , 128); } .filler-styles { height: 100%; border-radius: inherit; background-color: rgb(27, 150, 40); text-al ...

I'm looking for recommendations on where to begin learning about JavaScript touch events for web development. Any suggestions?

Seeking guidance on creating image galleries and content sliders that work with both touch and mouse events. Where should I begin exploring touch event implementation? I'm having difficulty locating official documentation. Are there any jQuery-suppo ...

Tips for eliminating stuttering when fixing the position of an element with JavaScript

I am currently facing an issue with a webpage I created where the text freezes when scrolled down to the last paragraph, while the images continue to scroll. Although my implementation is functional, there is noticeable jankiness when using the mouse wheel ...

The jQuery Animate feature springs to life with just a single click

I'm attempting to integrate jQuery's animate feature with a bookmark ID on my website. When I first click on the link, it jumps to the bookmark ID without any animation, but if I click the same link again, the animation works as expected. var Ti ...

increasing the size of the JSON object

I have a function that is being called multiple times utilizing jQuery to fetch different JSON data from an API. My aim is to calculate the total count of a specific portion of the JSON retrieved. Below is an example of what I currently have: getTheData( ...

When a textarea contains a new line, it will automatically add an additional row and expand the size of the textarea

Developed a form with the functionality to move placeholders in a textarea upwards when clicked. The goal is to increment the height of the textarea by 1 row for every line break. However, I am uncertain about what to include in the if statement of my Ja ...

Is it possible that the background color won't change on the second click?

Initially, my first click worked fine and successfully changed the background color. However, as soon as I added a second condition, it stopped working. var showBox = $('.show'); showBox.click(function(){ if (parseInt($(this).attr('v ...

Is there a way to verify the phone number input field on my registration form along with the country code using geolocation

I'm currently working on a registration form that includes an input field for telephone number. I'd like to implement a feature where, upon filling out the form, the telephone input field automatically displays the country code by default. Would ...

Guide to Changing the Value of a Textbox Using Form jQuery

For instance: <form id="example1"> <input type="text" name="example_input"> </form> <form id="example2"> <input type="text" name="example_input"> </form> In the code above, both text boxes have the same name. H ...

What is the best way to create square editor tabs in Eclipse without using swt-border-radius?

The design of Eclipse's rounded and/or swooshing tabs is starting to feel outdated in today's modern era. I thought that by adding the following line in my default.css file, I could get rid of the rounded corners: swt-corner-radius: 0px Howeve ...

Display information on a web page based on user input using HTML

I've hidden other p tags and divs using display:none, How can I make them visible after inputting my name? I'd like to type in my name and reveal all the content within the previously hidden div <form method="post"> <p> < ...

Fixed position of the element within a parent stacking context

How can I ensure that the #icon appears below the #dropdown in the following example? https://i.stack.imgur.com/GoBcR.png The position: fixed of #container seems to be creating a new stacking context for its children. Changing the position value fixes th ...

Achieving a sidebar that remains full height with CSS

Currently working on this page () where my aim is to create a sidebar that fills the entire height of the screen. The goal is for the sidebar, along with the black line on its right, to always reach the bottom of the viewport. JSFiddle Link Here's t ...

Separating stylesheets, head, and other elements in a curl response

After successfully using curl to retrieve an external site, I noticed that the results were interfering with my own content. The CSS from the external site was affecting my webpage's layout and z-index values were conflicting. I am seeking a solution ...

Achieving Dynamic Center Alignment of Filtered Node in SVG Using D3

I am currently implementing filter functionality for my d3 graph. The goal is to allow users to search for a specific node by label or ID, then re-render the graph to display the entire structure with the filtered node positioned at the center of the SVG e ...

Creating a choppy movement when switching between content with jQuery

I am experiencing a choppy effect when trying to toggle the content visibility with a button click. Can someone advise if there are any issues in how I have structured the markup? Also, is there a way to achieve a smoother toggle effect? View Code $(do ...

Unexpected JSON token error occurs in jQuery when valid input is provided

I encountered an error that I'm struggling to pinpoint. The issue seems to be related to the presence of the ' symbol in the JSON data. After thoroughly checking, I am positive that the PHP function json_encode is not responsible for adding this ...

Arrange elements both at the beginning and the end of a line using FlexLayout in Angular

Using the Angular flexlayout library in angular 7/8, I am trying to align 4 buttons on the left side (flex-start) and two checkboxes on the right side (flex-end) at the same level. I would prefer to achieve this layout using the flexlayout Angular library. ...

Save log discrepancies to a document

Upon completing my website for graduation, there is still one important feature I want to add. I would like to implement a script that sends the name of the website where it is installed, as well as any error messages, to my website. For instance: The fol ...

Positioning Elements Absolutely in Relation to List Items

I am looking to style a list item by adding background-color, border, and other properties. Below is the CSS and HTML I have tried so far. Additionally, I want to use the div element to position more absolute elements in relation to the li > div. ul { ...