BnJ
BnJ

Reputation: 1044

Select an image source in a list with a style in jQuery

I have this code in HTML :

<div id="thumbs_list">
    <ul id="thumbs_list_frame">
        <li id="thumbnail_260" style="display: none;">...</li>
        <li id="thumbnail_261" style="display: none;">...</li>
        <li id="thumbnail_262" style="display: none;">...</li>
        <li id="thumbnail_264" style="display: list-item;">
            <a href='mywebsite.com'>
                <img src="myphoto.png" alt="Photo"/>
            </a>
        </li>
        <li id="thumbnail_266" style="display: none;">...</li>          
    </ul>
</div>

I'm looking to get the source of the image who is in <li> with style="display: list-item;" (myphoto.png) with jQuery but I don't know how to do...

I tried this :

var firstThumbnailDisplay = $('#thumbs_list_frame li').css('display') == 'list-item';
var img = firstThumbnailDisplay.find("img").first().attr('src');

But it doesn't work.

Upvotes: 0

Views: 89

Answers (4)

Liam
Liam

Reputation: 29674

//declare an array (there could be multiple)
var listItems = [];
//Loop the items
$('#thumbs_list_frame li').each(function() {
   var $this = $(this);
   //check for value
   if ($this.css('display') === 'list-item') {
     //push item into array
     listItems.push($this);
   }
});

//listItems now contains all list items with display:list-item;

Fiddle

Upvotes: 1

SauriolJf
SauriolJf

Reputation: 412

Use :visible to find the one that is displayed and after with .find() and .attr() to acheive your goal.

var src = $('.result').html($('#thumbs_list_frame li:visible').find('img').attr('src'));

Here's a fiddle

Upvotes: 1

ZiNNED
ZiNNED

Reputation: 2650

This should work:

var src = $("#thumbs_list_frame li").filter(":visible:first").find("img").attr("src");

It finds the first visible (style not set to display: none;) li and gets the src attribute of the image inside it.

Upvotes: 1

Denat Hoxha
Denat Hoxha

Reputation: 945

Use the :visible selector.

var firstThumbnailDisplay = $('#thumbs_list_frame li:visible')

Upvotes: 1

Related Questions