What is the best way to show the initial image within every div that has the class name .className?

I am looking to only show the first image in each div with the class name "className."

This...

<div class="className">
  <p>Yo yo yo</p>
  <p><img src="snoop.jpg" /></p>
</div>
<div class="className">
  Helloooooo
  <img src="biggie.jpg" />
  <img src="tupac.jpg" />
  <img src="coolio.jpg" />
  Blah blah blah
</div>
<div class="className">
  <div><img src="dmx.jpg" /></div>
  <div><img src="willsmith.jpg" /></div>
</div>

Would display as...

[snoop.jpg]
[biggie.jpg]
[dmx.jpg]

Only the first image from each div with a className would be shown, without the additional content. The content is subject to change frequently.

Attempts at jQuery:

var imgarray = $(".className").find("img:first").attr('src');
for(i = 0; i < imgarray.length; i++){
  $('body').append('<img src=\"'+imgarray[i]+'\">');
}

...

(trying to obtain the SRC of each image...)

$('.className').each(function() {
  alert( $('img').attr('src') );
});

Having trouble getting it to work. Appreciate any help! I primarily focus on front-end HTML/CSS and am not very experienced with jQuery.

EDIT: Fixed typos (missing quote marks after image SRC's)

UPDATE: Thank you everyone for your assistance! Implemented the recommended solution as follows:

<style type="text/css">
  .className {
    display: none;
  }
</style>

<div class="className">
  <p>Yo yo yo</p>
  <p><img src="snoop.jpg" /></p>
</div>
<div class="className">
  Helloooooo
  <img src="biggie.jpg" />
  <img src="tupac.jpg" />
  <img src="coolio.jpg" />
  Blah blah blah
</div>
<div class="className">
  <div><img src="dmx.jpg" /></div>
  <div><img src="willsmith.jpg" /></div>
</div>

<script type="text/javascript">

  $('.className').each(function() {
    var imagesrc = $(this).find('img').first().attr('src') ;
    $('body').append( '<img src=\"' + imagesrc + '\">');
  });

</script>

Answer №1

To achieve your desired outcome, you will need to utilize the combination of .find() and .first().

Here is a sample code snippet for you to try out:

$('.className').each(function() {
  alert( $(this).find('img').first().attr('src') );
});

Answer №2

If you want to locate the first image within an element with a specific class name, you can utilize the .find() method along with the :first-selector

$('.className').find('img:first').show()

To see this in action, check out the demonstration here: Fiddle

Answer №3

If you're looking for a JavaScript solution to perform a linear search on each child node within elements with the class name className, look no further. One key consideration is whether each image is initially set to be hidden.

    <div class="className">
        <img style="display:none;" src="x" />
        <img style="display:none;" src="x" />
    </div>
   <div class="className">
        <img style="display:none;" src="x" />
        <img style="display:none;" src="x" />
    </div>
   <div class="className">
        <img style="display:none;" src="x" />
        <img style="display:none;" src="x" />
    </div>

<script>
 var el = document.getElementsByClassName('className');
  for(var a = 0; a < el.length; a++) {
   for (var i = 0; i < el[a].childNodes.length; i++) {
    if(el[a].childNodes[i].tagName == "IMG") {
        el[a].childNodes[i].style.display="block";
        console.log(el[a].childNodes[i].src);
        break;
    }
   }
  }

</script>

Check out the live demonstration on: Fiddle

Answer №4

Upon further examination of your inquiry, I have provided my response in three distinct parts.

To begin with, enclose text within a hidden span

$('.className').contents().filter(function(){
    return this.nodeType == 3 && $.trim(this.nodeValue).length;
}).wrap('<span class="spanhide" style="display: none;" />');

Next, conceal all images present

$('img', '.className').each(function () {
    var img = $(this);
    console.log("hide->" + img.attr('src'));
    img.hide();
 });

Lastly, reveal the initial image within each className division

$('img:first', '.className').each(function () {
    var img = $(this)
    console.log("show->" + img.attr('src'));
    img.show();
});

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

Utilizing Laravel routing for dynamic routes with optional parameters and asynchronous Ajax requests

I'm currently working on a user registration page and I've encountered an issue that's holding me back. The problem is that I am using the same view for both new registrations (where id will be null) and modifications (where id will be passe ...

Develop a MySQL table using AJAX and HTML within a Cordova application

I've been developing an app using Cordova and I'm looking to create a feature where users can create and join different rooms to perform various actions. Despite trying multiple tutorials and scouring the internet, I'm struggling to understa ...

Unique title: "Personalized on-click.prevent feature"

I'm having trouble coming up with a name for this concept, so I don't know what specific term to search for. I've checked out some directives, but I'm not convinced that's what I need. Essentially, I want to be able to do the follo ...

Execute custom time intervals for running jQuery ajax requests

I'm working on a jQuery ajax function that needs to be executed at specific intervals. It should not run on page load, but instead start after 5 minutes and then repeat every 5 minutes thereafter. Below is the code I am using: jQuery(document).ready ...

How can I close a dialog within an iframe in jQuery?

Suppose I initiate a dialog in this way: $('<iframe id="externalSite" class="externalSite" src="http://www.example.com" />').dialog({ autoOpen: true, width: 800, height: 500, modal: true, resizable: ...

Finding a solution to the type issue of error handling in Route Handler with NextJS

I'm working on a route handler located at app/api/transactions/route.ts. Here's a snippet of the code: import { NextRequest, NextResponse } from "next/server"; import { AxiosError } from "axios"; import axios from "../axi ...

Adjust the color of text as you scroll

Could you provide guidance on changing the color of fixed texts in specific sections of my portfolio website? Unfortunately, I can't share my lengthy code here, but would greatly appreciate it if you could illustrate with examples. Here's a refer ...

Refresh a Div using JSON content with Struts2 Jquery Plugin

Is there a way to dynamically reload the content of a div with just a specific part of a JSON object in it? The code provided works perfectly, but it displays the entire JSON object within curly braces. I want only one variable from the object to be shown ...

Form submission using Jquery not functioning properly in Firefox

Having an issue with the .post() function not working on Firefox, but functioning fine on Chrome. This is the code I am using: function saveD() { frm = $('#saveDetailsForm'); $.post(frm.attr('action'), frm.serialize(), fun ...

Applying a filter within an ng-repeat loop to act as a conditional

Is it possible to use the ng-repeat as a conditional in an efficient and optimal way? I am wondering if there is a way for code to be shown only if found selected is true, without having to create a new variable in the back-end. <div ng-repeat="c ...

Tips for displaying a button when hovering over it on large screens and larger sizes

I am trying to achieve a specific behavior where the button with class .bookmark-btn is only visible on md size screens and smaller at all times. However, on lg size screens and bigger, it should only appear when hovered over. How can I accomplish this? Cu ...

Having issues with Vue.js v-repeat not displaying any content

I have just started learning about vue.js. I attempted to display a simple list, but it is not showing anything. Here is my code: <html> <head> <title>VUE Series</title> <link rel="stylesheet" type="text/css" ...

What is the best way to retrieve all the keys from an array?

I am looking to retrieve the address, latitude, and longitude data dynamically: let Orders= [{ pedido: this.listAddress[0].address, lat: this.listAddress[0].lat, lng: this.listAddress[0].lng }] The above code only fetches the first item from the lis ...

Accessing the parent element within a hover declaration without explicitly naming it

I am facing a challenge with three nested divs, where I want to change the color of the children when the parent is hovered. However, I prefer not to assign a specific class name to the parent element. The issue arises because the children have their own ...

Issue with jQuery delay() causing animation disruptions

I've implemented a drop-down menu that functions smoothly, but I'd like to enhance it by making the drop-down stay visible for an additional 500ms after the user hovers out of the box. My attempt at using .delay(500) led to the animation getting ...

Attempting to feed information into a computed property within Vue.js

I'm currently working on a project that involves Vue JS, specifically Nuxt JS. Within my web page, I am required to render certain classes onto an element that exists within a v-for loop. To achieve this, I need to pass data to a computed property alo ...

Determine the height of an image using JavaScript

How can I retrieve the height of an image in a JavaScript function? When I use the code: var image_height = $(image).height(); The value of image_height is 0, even though my image definitely has non-zero height. Is there a different method to accurately ...

The HTML form is not displaying any content and instead is returning "Not a Number

I've been struggling to create a form that can generate a numerical value based on the input from two fields. Specifically, I need to calculate the output by subtracting the product of two values - one entered in an input field and another selected vi ...

Parsing JSON data from a PHP response using jQuery

Here is the code snippet I am working with using jQuery: var dataString = "class_id="+class_id; $.ajax({ type: "POST", url: "page.php", data: dataString, success: function (msg) { //stuck here }, error: function () { ...

When utilizing JSON data in node.js, the .find() method may return undefined

I am currently working on a node server and my goal is to display JSON data when a specific ID is clicked. I have configured a dynamic URL that will retrieve the data of the clicked video using parameters and then compare it with the data in the JSON file ...