开发者

Select the .next() element with a specific attribute JQUERY

开发者 https://www.devze.com 2023-03-23 00:49 出处:网络
This is what I have : $(\"#comment\").next().attr(\'shown\',0).fadeIn(); I\'m trying to show the next comment that is hidden on the page.however, I\'m trying to do two comments shown at a time, so

This is what I have :

$("#comment").next().attr('shown',0).fadeIn();

I'm trying to show the next comment that is hidden on the page. however, I'm trying to do two comments shown at a time, so if you click the first one, the second one is n开发者_运维百科ext. So I've given a shown attribute. I would like to select the NEXT with the attribute shown=0. The above does not work. I believe it would be next(tr[shown=0]) but i can't get that to work (i'm in a table looking for the next row)

any help is appreciated!


next can only return the immediate next sibling.

You can call nextAll, which returns all subsequent siblings, with the :first selector to get the first matching one:

$(...).nextAll("tr[shown=0]:first")


I know this is an old post, but just going by the title the first answer threw me off. However @SLaks answer is exactly what I was looking for personally and fixed my issue.

This actually helped me out a lot in a completely different situation while just happening to find this post. This answer is the best one as mentioned in his response.

The issue I had was something similar to something below and I had to pick from a specific attribute in order to get the next one with similar attribute name, but different value.

<div class="blah" data-field="sometext" data-index="0"></div>
<div class="bar"></div>
<div class="blah" data-field="sometext" data-index="1"></div>


$("div[data-field='sometext'][data-index='0']")
    .nextAll("div[data-field='sometext']:first"); 

Above returns

  <div class="blah" data-field="sometext" data-index="1"></div>

Hope this helps someone else as it helped me out greatly


SLaks answer will work, but I would consider not using custom attributes in your HTML as it might confuse another developer down the road. Something like this would use no custom attributes:

<style>
.hidden {
    display:none;   
}
</style>

<script>
$(document).ready(function(){ 
   $('.showmore').click(function(){ 
       $(this).parent().nextAll(':hidden:first').removeClass('hidden');
   })
});
</script>

<div id="comments">
<div class="comment" id="comment1">
    Test comment        
    <a href="#" class="showmore">Show More</a>
</div>
<div class="comment" id="comment2">
    2nd test comment
    <a href="#" class="showmore">Show More</a>
</div>
<div class="comment hidden" id="comment3">
    3rd test comment
</div> 
<div class="comment hidden" id="comment4">
    4th test comment
</div>   
</div>

Demo

0

精彩评论

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