How to target the attribute value of an image element that has a specific parent class using jQuery

I'm working with a list that looks like this:

<ul>
    <li><div class="thumb"><img src="image-1.jpg"></div></li>
    <li><div class="thumb"><img src="image-2.jpg"></div></li>
    <li><div class="thumb selected"><img src="image-3.jpg"></div></li>
</ul>

Is there a way to specifically target the img tag with the div parent having the "selected" class and retrieve its src attribute?

Answer №1

If you want to retrieve the current value of the src:

let currentSrc = $("div.selected img").attr("src")

To update the src:

$("div.selected img").attr("src", "newImage.jpg");

(Please note that the selector "div.selected img" will select all images within that div, which is fine if there is only one. If there are multiple images, .attr("src") will change the source of the first image only, but .attr("src", "newImage.jpg") will modify them all.)

Answer №2

Instead of providing a brief answer, you have the choice to opt for selecting the img element and then applying a filter:

$('img').filter(function() {
    return $(this).closest('div.selected').length;
}).attr('src');

However, this method may not be very efficient, as shown in a jsPerf test.

For more information, check out the following references:

Answer №3

$(".thumbactive").find("img").attr("src");

Choose the Class .thumbactive, find its child img, and retrieve the src attribute.

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

The font size on my website fluctuates up and down every time I refresh the page or navigate to a different one

I am currently in the process of updating my research lab's website using a Jekyll framework with Bootstrap. However, I have encountered an issue where the font size grows slightly whenever I navigate to a new page or refresh the current one, before r ...

Unable to load the type [ProjectName].WebAPIApplication in the Web API application

I am currently working on a .Net Web Application that utilizes the Web.API Project Properties indicating it is built with .Net 4.5. Within my web page, the code snippet below is used to call one of the methods: $.ajax({ type: 'POST', u ...

Display the appropriate selection choices based on the knockout condition

In my HTML page, there is a dropdown with certain conditions that determine which options should be rendered in the select element. My attempt at achieving this: <select> <!-- ko if: condition() --> <option value="1">1& ...

The issue with Go Code is that it fails to display the JSON data received from a jQuery

Problem Description The issue I am facing is that Go Code is not displaying the posted JSON value from jQuery AJAX. Main Go Code routing := chi.NewRouter() routing.Post("/authenticate", AuthenticateRouter) Go Code Snippet func AuthenticateRouter(w http. ...

New to CSS/Ruby - What causes two adjacent buttons to have varying sizes?

The varying sizes of my search and login buttons located beside each other are puzzling me. Could it be due to the fact that the search button is enclosed within a submit_tag argument while the login button is not? If this is indeed the case, how can I mak ...

The inefficacy of the JQUERY validation plugin, AJAX, and PHP integration

After diving into learning AJAX for submitting forms, I've encountered a roadblock. The data I submit doesn't seem to reach the PHP file as expected, and I can't figure out why it's failing. Here's my HTML: <div class="col-md- ...

Passing two variables through a Javascript URL to dynamically update a dropdown menu based on the specified values

What is the best way to send two variables to a JavaScript function in order to modify the dropdown list according to those values? $(document).ready(function() { $("#date").change(function() { $(this).after('<div id="loader">& ...

Learn how to retrieve data using the $.ajax() function in jQuery and effectively showcase it on your HTML page

Can someone assist me with extracting data from https://jsonplaceholder.typicode.com/? Below is the AJAX call I'm using: $.ajax({ url: root + '/posts/', data: { userId: 1 }, type: "GET", dataType: "json", success: function(data) { ...

manipulating dropdown visibility with javascript

I'm feeling a bit lost on how to structure this code. Here's what I need: I have 5 dropdown boxes, with the first one being constant and the rest hidden initially. Depending on the option chosen in the first dropdown, I want to display the corres ...

Is it achievable to modify the appearance of the "Saved Password" style on Firefox?

After creating a login page that initially had a certain aesthetic, I encountered an issue when saving login data in Firefox. The saved login page took on a yellow-ish tint that was not present in my original design: https://i.sstatic.net/LURG3.png I am ...

How to Make Buttons Vanish and Reappear

Check out this fiddle for a picture button 'scroller' that I created. It may not be perfect, but my main focus is on making the arrow buttons fade in and out when reaching the end of the picture order. I am considering using a JavaScript functio ...

Interested in learning how to filter nested tables?

After successfully integrating a filter code snippet, I encountered an issue with the filter not recognizing data tables that can only be inserted as nested tables. Due to my limited knowledge of JavaScript/CSS, I'm unsure if this problem can be resol ...

When collapsing an accordion, Bootstrap radio buttons fail to properly select

I have attempted various methods to achieve the desired functionality of having the accordion content close and open accordingly when checking a radio button, while also having the button visually appear as 'checked'. For a more in-depth example, ...

What is the best method to update the content of one div with content from another page using AJAX?

Having trouble achieving smoother page loads? My goal is to utilize AJAX to specifically fetch a certain div from another page and then swap out the content of a div on this current page with the response. Below is my JavaScript script that uses AJAX to r ...

Struggling to send data to Wufoo API using PHP and AJAX

I'm still getting the hang of PHP and attempting to send data to a Wufoo Form that includes the fields shown below: https://i.sstatic.net/yoOgy.png However, when trying to POST information to it, I keep receiving a 500: Internal Server Error along w ...

Creating diamond-shaped columns and rows in HTML using the Bootstrap framework is a fun and creative way to

Recently, I tackled the challenge of building a website based on a specific design. Within this design, there was a div element that included an image link. Despite my efforts, I found myself at a loss on how to proceed with this task. Here is the snippet ...

Preserve the output from the jQuery ajax request

I have created a custom function that calls an ajax request and saves the response data to a variable before returning it. It always shows '0' as the return value, but the alert displays numbers like 3712. Below is the implementation of the func ...

Issue with AJAX and Jquery auto form update functionality malfunctioning

On my form page, here is the code snippet: <form action="/register-process" method="post" id="form1"> <script type="text/javascript"> jQuery(document).ready(function($) { $(document).on('focusout', '#dateenglish', function ...

"Including Span icons, glyphs, or graphs within a table cell in AngularJS based on a specified condition or numerical

I'm attempting to incorporate span icons/glyph-icons using Angular within a td before displaying the country. I've utilized the code below to achieve this, but I'm looking for a more dynamic and elegant solution. Your assistance is greatly a ...

Using the jQuery .submit() function in conjunction with Angular

Is there a way to submit a form using an Angular controller? Also, how can we invoke jQuery functions within Angular? <form id="flightRules" target="_blank" action="<?= Yii::$app->request->baseUrl ?>/site/farerules" method="post"> ...