neethu
neethu

Reputation: 121

how do I display the content of <p> in jquery

<div class="albumclass">
  <img width="100" height="100" data-assigned-id="9" src="/Content/images/fold.png">
  <p>15Sep2015</p>
</div>

The above code is generated dynamically through jQuery. After that I need to display the content of <p> ie., '15Sep2015' by clicking on the above image. How can I get this? I used the below code:

$('.album_inner').on('dblclick', '.albumclass img', function (e) {
  var txt = $(this).closest("p").text();
  alert(txt);
}

But that alerts nothing.It not possible to take content implicitly because a lot of similar div will be there.

Upvotes: 2

Views: 71

Answers (4)

Zihan.Zhou
Zihan.Zhou

Reputation: 53

Why not try adding a class to the 'p' tag so that u can get the element by a class selector and see var text = $('.class').text();alert(text); or u may try $(document.body).on('click','.class',function(){ });

Upvotes: 0

Sanjay Verma
Sanjay Verma

Reputation: 417

$('.albumclass').on('click', function(){
var p_text = $(this).children('p').text();
alert(p_text);
});

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You can go up to parent div and find p using find() :

$('.album_inner').on('dblclick', '.albumclass img', function (e) {
    var txt = $(this).closest("div").find('p').text();
    alert(txt);
}

Hope this helps.

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

The .closest() gets the parent. So use .siblings() or .next. I have used .next():

$('.album_inner').on('dblclick', '.albumclass img', function (e) {
  var txt = $(this).next("p").text();
  alert(txt);
}

Upvotes: 2

Related Questions