Recuperación de ID de una imagen específica

How can I get the ID of an image according to the following situation

JQUERY

$(".favoritar").click(function (data) {
    // Here I want recover the previous IMG ID, that in this case should be
    // DannaWhite, but the following code returns <img src="../../fotos_teste/05.PNG" id="DannaWhite" width="50" height="50" />
    alert($(this).parent().closest(".bxFotoUsuarioLateral").html());
});

HTML

<div class="modal-header" style="background-color: #0F4265 !important;">
    <div class="bxFotoUsuarioLateral">
        <img src="../../fotos_teste/05.PNG" id="DannaWhite" width="50" height="50" />
    </div>

    <div class="icon-star"></div>     

    <img src="../../Images/favorito.png" class="favoritar" id="favoritarPost1" style="float: right; cursor: pointer;" />
    <h4 class="modal-title" style="margin-left: 70px;">Cancelamento de Contrato <span id="idImovelAlteraStatus"></span></h4>
    <span class="txtSample05" style="text-transform: none; margin-left: 40px;">Há 2 horas</span>
</div>

preguntado el 28 de mayo de 14 a las 14:05

$(this).prop('id')? -

No, I'm in the click action of the class .favoritar, the image that I want its before -

ok, $(this).closest('div.modal-header').find('.bxFotoUsuarioLateral > img').prop('id'). If there are more than one image in the div you can .map() the ids and get an array. -

3 Respuestas

If it's only one image:

var id = $(this).closest('div.modal-header')
                .find('.bxFotoUsuarioLateral > img').prop('id');

If you want an array of ids, regardless of the amount of images:

var ids = $(this).closest('div.modal-header')
                .find('.bxFotoUsuarioLateral > img')
                .map(function(){
                    return this.id;
                }).get();

contestado el 28 de mayo de 14 a las 14:05

Puedes usar:

$(this).closest(".modal-header").find(".bxFotoUsuarioLateral img").attr("id");

or

$(this).parents(".modal-header").find(".bxFotoUsuarioLateral img").attr("id");

De demostración

contestado el 28 de mayo de 14 a las 14:05

Además, use prop('id') - Johan

@mplungjan: hey thanks. i was stucked making fiddle. Thanks for catch. fixed it now. - milind anantwar

Ejemplo de trabajo

$(".favoritar").click(function (data) {
  // Here I want recover the previous IMG ID, that in this case should be
  // DannaWhite, but the following code returns undefined
  alert( $(this).parents(".modal-header").find(".bxFotoUsuarioLateral img").attr("id"))
});

contestado el 28 de mayo de 14 a las 15:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.