Vian Ojeda Garcia
Vian Ojeda Garcia

Reputation: 867

jQuery can't catch the parent element

I am trying to access the parent element up to the button element to modify its css. I can access the span element via id. But when I try to go to the parent img it says undefined

Here is my html code

<button type="button" class="buttonLike">\
    <img src = "../Image/thumbsUp.png" clas="test">\
            <span class="postID" id=' + idPost + '>' + likesPost + '</span>\
    </img>\
 </button>\

and here is my jquery code that access the span element

$.each(result, function (index,data) {
                var liked = data.liked;
                if (liked == true) {
                    console.log($("#" + postId).parent("img").attr("src"));
                }
   });

How can i do this right.

Upvotes: 0

Views: 56

Answers (4)

Rajkumar Somasundaram
Rajkumar Somasundaram

Reputation: 1270

I have closed the image and made the span as sibling of parent;

In this code snippet I have provided both jquery approach and pure js approach. Hope this helps.

//jquery approach
console.log($(".postID").siblings('.test').attr("src"));

//pure js
console.log(document.getElementsByClassName("postID")[0].previousElementSibling.getAttribute('src'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="buttonLike">
<img class="test" src="http://cdn3-www.dogtime.com/assets/uploads/gallery/goldador-dog-breed-pictures/puppy-1.jpg"/>
  <span class="postID" id=' + idPost + '>' + likesPost + '</span>    
 </button>

Upvotes: 0

Bhargav Chudasama
Bhargav Chudasama

Reputation: 7161

try using this

.parent().find('img').attr('src')

console.log($("#idPost").parent().find('img').attr('src'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="buttonLike">
    <img src = "Image/thumbsUp.png" class="test">
    <span class="postID" id='idPost'>likesPost </span>
   
 </button>

Upvotes: 1

surya surakhman
surya surakhman

Reputation: 92

I think you should not wrap the span inside the img. that will make more easy for you. But if you still want to. try this. $("#postId").closest("img");

Upvotes: 1

Saeed M.
Saeed M.

Reputation: 2361

img element is self-closing. try this:

<button type="button" class="buttonLike">\
    <img src = "../Image/thumbsUp.png" clas="test">
    <span class="postID" id=' + idPost + '>' + likesPost + '</span>\
 </button>

and get it with jquery:

  console.log($("#" + postId).parent().find("img").attr("src"));

Upvotes: 2

Related Questions