How do I select a sibling element using jQuery?

佐手、 提交于 2019-11-27 01:26:33

问题


Can you help me with this jQuery selector?

$(".auctiondiv .auctiondivleftcontainer .countdown").each(function () {
    var newValue = parseInt($(this).text(), 10) - 1;
    $(this).text(newValue);

    if (newValue == 0) {
        $(this).parent().fadeOut();
        chat.verify($(this).parent().parent().attr('id'));
    }
});

Basically, I want to select the element with .bidbutton class that belongs in the same parent as the .countdown in the each loop:

<div class="auctiondivleftcontainer">
    <p class="countdown">0</p>
    <button class="btn primary bidbutton">Lance</button>                            
</div>  

And then apply this to that button:

$(button here).addClass("disabled");
$(button here).attr("disabled", "");

回答1:


Use jQuery .siblings() to select the matching sibling.

$(this).siblings('.bidbutton');



回答2:


$(this).siblings(".bidbutton")



回答3:


Here is a link which is useful to learn about select a siblings element in Jquery.

How do I select a sibling element using jQuery

$("selector").nextAll(); 
$("selector").prev(); 

you can also find an element using Jquery selector

$("h2").siblings('table').find('tr'); 

For more information, refer this link next(), nextAll(), prev(), prevAll(), find() and siblings in JQuery




回答4:


$("h2").siblings().css({"color": "blue"});

Details are described in the source below:

http://www.namasteui.com/traversing-siblings/




回答5:


jQuery provides a method called "siblings()" which helps us to return all sibling elements of the selected element. For example, if you want to apply CSS to the sibling selectors, you can use this method. Below is an example which illustrates this. You can try this example and play with it to learn how it works.

$("p").siblings("h4").css({"color": "red", "border": "2px solid red"});




回答6:


Since $(this) refers to .countdown you can use $(this).next() or $(this).next('button') more specifically.




回答7:


Try -

   $(this).siblings(".bidbutton").addClass("disabled").attr("disabled", "");



回答8:


If you want to select a specific sibling:

var $sibling = $(this).siblings('.bidbutton')[index];

where 'index' is the index of the specific sibling within the parent container.




回答9:


also if you need to select a sibling with a name rather than the class, you could use the following

var $sibling = $(this).siblings('input[name=bidbutton]');



回答10:


you can select a sibling element using jQuery

 <script type="text/javascript">
    $(document).ready(function(){
        $("selector").siblings().addClass("classname");
    });
 </script>

Demo here



来源:https://stackoverflow.com/questions/7463242/how-do-i-select-a-sibling-element-using-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!