开发者

Get the content of siblings elements with jQuery

I need to get the content of some specific elements using jquery, the problem is that i have the same element repeating on my page:

<div class="content">
   <img alt="" src="">
   <p class="txt">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
   <p class="info">Lorem ipsum dolor...</p&g开发者_C百科t;
   <ul>
     <li><a class="uiButton">Test</a></li>
   </ul>
 </div>

So, the div.content repeat on my page many times and I want to get only the contents of the div that holds the button was clicked. I've added a onclick event on the .uiButton and tried to use parent(".txt") or siblings(".txt"), but dont seems to work...

$(".uiButton").click(function(){ 
  var txt = $(this).parent(".txt").text(); 
}


.txt isn't a parent, and even then it has to be a direct parent (.parent() matches the immediate parent if it matches the selector), instead you need:

$(".uiButton").click(function(){ 
  var txt = $(this).closest("ul").siblings(".txt").text(); 
});

The alternative is to go all the way up to .content (via .closest()) to be safe then traverse down with .find():

$(".uiButton").click(function(){ 
  var txt = $(this).closest(".content").find(".txt").text(); 
});


You need to go up to the wrapper and down, you can go to siblings, but in this case it will be harder.

$(".uiButton").click(function(){ 
  var txt = $(this).closest('.content').find('.txt').text(); 
}


$(this).closest('p.txt');

Might work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜