user2024438
user2024438

Reputation:

How to find the previous element of the specified element in jquery

I'm trying to find the previous img element present before the specified element. But when I run my code it returns undefined.

My code is:

 $(document).on('keypress','#sendComment', function(e) {
    if(e.keyCode==13){
        var itemId=$('#findbefore').prev('.SharedImage');//
        console.log(itemId);
        var dataid=itemId.data('id');
        var dataalid=itemId.data('alid');
        var datashareid=itemId.data('shareid');
        var alt=itemId.attr('alt');
        alert(dataid +' '+dataalid+' '+datashareid+' '+alt);
    }
});

This was printing Object[] in console and undefined undefined undefined undefined in alert.

And my divs are :

 <div id="S04" class="snew" style="display: block;">
 <div class="author-image"></div>
 <span>ajay shared the image xyz</span>
 <div class="s-content">
 <div class="s-message"></div>
 <div class="shpicture">
 <img class="SharedImage" width="100%" height="100%" data-shareid="1" data-alid="1" data-id="1" alt="xyz" src="data:image/jpeg;base64,">
 </div>
 </div>
 </div>
 <div class="SPcommentbox" id="findbefore">
 <div class="comment">
 <div class="commenter-image"></div>
 <div class="addcomment">
 <input id="sendComment" class="commentbox" type="text" placeholder="Write a comment...">
 </div>
 </div>
 </div>

I need to find the attribute values of img. When user press enter button.

Note : I'm adding these divs with jQuery

Please anyone help me to solve this ... Thanks...

Upvotes: 1

Views: 90

Answers (1)

Alnitak
Alnitak

Reputation: 339975

.prev() will only match the immediately preceding element, and if you've supplied a selector, only if it matches that selector.

Given the existing HTML snippet you need:

$('#findbefore').prev().find('.SharedImage');

However I'm concerned about whether there might be multiple such elements on the page? You may get a fuller answer if you supply more HTML.

For example, you might be better off with:

$(this).closest('.SPcommentbox').prev().find('.SharedImage');

Alternatively, if there's guaranteed only one .sharedImage on the page, then you should give it an ID instead of a class, and access it directly:

$('#SharedImage')

Upvotes: 2

Related Questions