Skindeep2366
Skindeep2366

Reputation: 1559

Getting the Id attribute from an Image in a div

I have a div that contains 1 to many images with next and previous image buttons. When a user clicks the next/previous button the current image style is changed from display:block to display:none using jquery. I need to get the ID attribute from the current image that is showing ie. has the display:block style applied.

<div id="propPhotos" name="propPhotos">
   <div id="propPhotsDivList">
        <div id="imageNameId0" style="display:block">
             <img src="/PropertyImages/1/171fc210b4584f41936a078c4176c7e0.jpg" height="200" width="200" id="3"/>
        </div>
        <div id="imageNameId1" style="display:none">
            <img src="/PropertyImages/1/114810f0067749eda8049d2f8269dd00.jpg" height="200" width="200" id="4"/>
        </div>
        <div id="imageNameId2" style="display:none">
            <img src="/PropertyImages/1/8.jpg" height="200" width="200" id="15"/>
        </div>
        <div id="imageNameId3" style="display:none">
            <img src="/PropertyImages/1/e8f182ab645549b399cebc67ed996d151.jpg" height="200" width="200" id="25"/>
        </div>
    </div>
    <div>
        <div class="row">
            <input type="button" id="NextImage" value="Next Image" onclick="ImageNext()" /><input type="button" id="PrevImage" value="Previous Image" onclick="    ImagePrev()" />
        </div>
        <div class="row">
            <button type="button" class="AddImage">Add Image</button><button type="button" class="RemoveImage">Remove This Image</button>
        </div>

    </div>

This is the path I am currently on which is in the next and previous image click handlers.

        CurrentImageId = document.getElementById("imageNameId" + id).children('img').attr('id');

So when the user clicks either button its supposed to assign the id value to the CurrentImageId. This does not work for one and does not help on the initial load when neither next or previous image buttons have been clicked.

Upvotes: 0

Views: 646

Answers (2)

Hamid Bahmanabady
Hamid Bahmanabady

Reputation: 665

$('#propPhotsDivList').children('div:not(:hidden)').attr('id');

Upvotes: 0

Johan
Johan

Reputation: 35194

Well, there are a few different ways as far as the initial load is concerned. Here are a couple of examples:

Using the :visible selector:

var currentImageId = $('#propPhotsDivList > div:visible > img').prop('id');

Or perhaps combined with filter():

var currentImageId = $('#propPhotsDivList img').filter(function(){
    return $(this).parent('div').is(':visible');
}).prop('id');

If the divs are hidden and shown correclty using your click handlers, you can use the same functionality inside them as well.

Upvotes: 1

Related Questions