A step-by-step guide on extracting the image source from a targeted element

Here is a snippet of my HTML code containing multiple items:

<ul class="catalog">
  <li class="catalog_item catalog_item--default-view">
    <div class="catalog_item_image">
      <img src="/img/01.png" alt="model01" class="catalog_item_icons__big-foto">
   </div>
   <ul class="catalog_item_icons">
      <li class="catalog_item_icons__preview"><img src="/img/01-01.png" alt="01" class="catalog_item_icons__preview--foto-small"></li>
      <li class="catalog_item_icons__preview"><img src="/img/01-02.png" alt="02" class="catalog_item_icons__preview--foto-small"></li>
      <li class="catalog_item_icons__preview"><img src="/img/01-03.png" alt="03" class="catalog_item_icons__preview--foto-small"></li>
   </ul>

In this scenario, I am attempting to switch the source attribute (src) of img.catalog_item_icons__big-foto with that of img.catalog_item_icons__preview--foto-small

This should occur when clicking on the list item (li) element within its parent ul.catalog.

Here's what I have attempted:

$(".catalog_item_icons__preview").each(function () {
  $(this).on("click", function() {
    console.log('Clicked preview!');
    // obtain the fileName of the image
    var smallImagePath = $(this).children("img").attr("src");
    console.log("small image: " + smallImagePath);
    var $bigPreview = $(this).closest('img.catalog_item_icons__big-foto').attr("src");

    // log the src of the nearest big image in the console
    console.log($bigPreview);

  });

});

Although I can retrieve the src of the small image, I encounter issues accessing the src of the image higher up in the hierarchy. Console output: undefined. Troubleshooting why remains puzzling :(

Answer №1

To implement this functionality, you can follow the steps outlined below:

$(document).ready(function() {
    //Define a script to execute when an item is clicked
    $('.catalog_item_icons li').click(function() {
         //Capture the source of the clicked image
        _src = $('img', this).attr('src');
         //Identify the parent .catalog_item--default-view element of the clicked item
        _obj = $(this).parents('.catalog_item--default-view');
         //Update the source attribute of the .catalog_item_icons__big-foto within the _obj element
        $('.catalog_item_icons__big-foto', _obj).attr('src', _src);
    });
});

Answer №2

When searching for catalog_item_icons__big-foto, keep in mind that it is not a direct ancestor so the closest method will not locate it. This method first looks at itself and then its parents. The element you are seeking is actually a child of one of those parents.

The easiest solution is to locate the top li and find the image from there.

$(this).closest(".catalog_item catalog_item--default-view")
    .find('img.catalog_item_icons__big-foto')

Another option is to identify the parent ul, locate the previous sibling, and then find the image within that element.

Answer №3

The issue lies here: The closest() method retrieves the nearest ancestor of the chosen element. An ancestor could be a parent, grandparent, great-grandparent, and so forth.

 var $bigPreview = $(this).closest('img.catalog_item_icons__big-foto').attr("src");

You can simply utilize a class that suits your needs.

 var $bigPreview = $('img.catalog_item_icons__big-foto').attr("src");

Answer №4

Here is a helpful piece of code that is working for me when I check the console:

$("li.catalog_item_icons__preview").on("click", function(){
    // get image fileName
    var smallImagePath = $(this).children("img").attr("src");
    console.log("small image: " + smallImagePath);
    var bigPreview = $(this).parent('ul').siblings(".catalog_item_image").children(".catalog_item_icons__big-foto").attr("src");

    // print in console src of nearest big image
    console.log(bigPreview);
});

$("li.catalog_item_icons__preview").on("click", function(){
    // get image fileName
    var smallImagePath = $(this).children("img").attr("src");
    console.log("small image: " + smallImagePath);
    var bigPreview = $(this).parent('ul').siblings(".catalog_item_image").children(".catalog_item_icons__big-foto").attr("src");

    // print in console src of nearest big image
    console.log(bigPreview);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="catalog">
  <li class="catalog_item catalog_item--default-view">
    <div class="catalog_item_image">
      <img src="/img/01.png" alt="model01" class="catalog_item_icons__big-foto">
   </div>
   <ul class="catalog_item_icons">
      <li class="catalog_item_icons__preview"><img src="/img/01-01.png" alt="01" class="catalog_item_icons__preview--foto-small"></li>
      <li class="catalog_item_icons__preview"><img src="/img/01-02.png" alt="02" class="catalog_item_icons__preview--foto-small"></li>
      <li class="catalog_item_icons__preview"><img src="/img/01-03.png" alt="03" class="catalog_item_icons__preview--foto-small"></li>
   </ul>
  </li>
</ul>

Answer №5

Give this a try

$(".catalog_item_icons__preview").click(function() {
  $(".catalog_item_icons__big-foto").attr("src", $(this).children("img").attr("src"));
  console.log($(".catalog_item_icons__big-foto").attr("src"));
});
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="catalog_item_image">
  <img src="/img/01.png" alt="model01" class="catalog_item_icons__big-foto">
</div>
<ul class="catalog_item_icons">
  <li class="catalog_item_icons__preview">
    <img src="/img/01-01.png" alt="01" class="catalog_item_icons__preview--foto-small">
  </li>
  <li class="catalog_item_icons__preview">
    <img src="/img/01-02.png" alt="02" class="catalog_item_icons__preview--foto-small">
  </li>
  <li class="catalog_item_icons__preview">
    <img src="/img/01-03.png" alt="03" class="catalog_item_icons__preview--foto-small">
  </li>
</ul>

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

Exploring the capabilities of storing and retrieving nested objects within a React database

I'm having trouble retrieving nested items from my database. This is how my database is structured: GET /dwelling/room/ [ { "room_id": 1, "room_name": "Living Room", "room_data": [ { "id": 1, ...

Issues with Angular's *ngIf directive not functioning correctly

Within my template, I have a block of HTML that controls the visibility of a div. <div *ngIf="csvVisible"> <p>Paragraph works</p> </div> This particular code snippet belongs to my component. export class SettingsComponent imple ...

Runtime Error: Invalid source property detected - Firebase and Next.js collaboration issue

Currently, I am developing a Next.js application that retrieves data from a Firestore database. The database connection has been successfully established, and the data is populating the app. However, I am facing an issue with displaying the image {marketpl ...

Mysterious Loop in JavaScript Unfolding with Three.Js

In order to expand my knowledge of Angular and Three.Js, I am currently working on a prototype SPA that showcases different 3D elements rotating. There are several Angular templates accessible through a navigation menu, each displaying unique rotating elem ...

Adding li elements dynamically, how can we now dynamically remove them using hyperlinks?

Please refrain from using jQuery code, as my main focus is on learning javascript. I am currently experimenting with adding li items dynamically to a ul when a button on the HTML page is clicked. Here's a sample implementation: HTML: <ul id="myL ...

Exploring the attributes of ExtJS display objects

I am looking for a way to efficiently display JSON content from a servlet in a browser using a list format. While I could use the definition list tag in pure HTML, I need to load everything dynamically without manually parsing and creating the HTML code. ...

Using Jquery to append a selector to an object that has already been selected

Hey there, When utilizing the standard selector, I've managed to choose the grandparent of an input text field (which is essentially a <td> element), and then used .next() function to pick the next row. var nextOne = $(this).parent().parent(). ...

changing web pages into PDF format

I need to convert HTML to PDF on a Linux system and integrate this functionality into a web application. Can you suggest any tools that are capable of doing this? Are there any other tools I should consider for this task? So far, I have attempted the foll ...

Integrating React js with Layout.cshtml: Mastering the Fusion of React Routing and ASP.NET MVC Routing

My current project involves an ASP.NET MVC core application with the View written in cshtml. The routing follows the conventional asp.net mvc routing pattern. However, I've recently implemented a new module using React JS. Now, I'm faced with the ...

Sharing information between pages in React through Router

I am struggling to transfer a single string from one page to another using react router and only functional components. I have created a button that links my pages, but I can't seem to pass the string successfully. Here is an example of the code on th ...

Modifying HTML Email to Achieve Consistent Rendering Across Various Email Platforms

While creating an HTML based email for our subscribers, I noticed that it renders differently in various email clients. The main issue arises in Outlook 2003 where the main picture is offset to the left and the grid boxes vary in height depending on the co ...

Challenges encountered when bringing in modules from THREE.js

Is there a way for me to import the custom geometry file called "OutlinesGeometry.js" from this link? I've attempted to import it like this: <script type="module" src="./three/build/three.module.js"></script> <scrip ...

The smooth scrolling feature fails to function properly in Lenis when clicking on links with specified IDs

Is there a reason why the scroll-behavior: smooth property doesn't function properly when Lenis library for smooth scrolling is included? It seems to work fine when the Lenis code is commented out, but once it's added back in, the scrolling isn&a ...

centering the text within the div for perfect alignment

I've been attempting to customize a Register form. My goal is to position the heading in the center of the div while having another login form located right beside it. Using flexbox, I styled them and then applied justify-content as center. Additiona ...

Quickest method to detect IE

Is there a way to detect IE and prompt the user to change their browser? <!--[if IE]> <p>rrff</p> <script type="text/javascript"> alertify.alert("Please change your browser"); </script> <![endif]--> <!--[if gte IE 8] ...

The $http service encounters an error while attempting to retrieve a JSON file from the server

When attempting to fetch a file from the server, I utilize the $http service in the following manner: $http({url: url, method: "GET", withCredentials: true}); For some mysterious reason, an exception is only thrown when trying to retrieve JSON files from ...

Choosing each item from a lineup, one by one

Currently, I am in the process of developing a small website with multiple pages. The main requirement for this project is to have a vertical menu on the home page. Implementing the menu was relatively easy. I successfully added a hover effect to the vert ...

Is it simple to host a vue.js web application within the assets folder of a sails.js project?

Currently, I am in the process of learning how to utilize Sails.js and vue.js. My goal is to develop a small application where a vue.js application is situated within the assets/ directory of Sails.js. The challenge I'm facing is figuring out how to s ...

When using Node.js with Express and ssh2, my data structures remain intact without any resets when loading web pages

To display jobs sent by users to a cluster, the code below is used (simplified): var split = require('split'); var Client = require('ssh2').Client; var conn = new Client(); var globalRes; var table = [["Head_1","Head_2"]]; module.exp ...

Enhance visual content using JavaScript to filter images in React

I am currently developing a React app with multiple pages that are being imported into another component page. The structure of one of my pages looks like this: export default class Product1 extends React.Component { render() { return ( <di ...