How to select an element's parent and the parent's siblings

后端 未结 7 1419
花落未央
花落未央 2020-12-08 12:53

I have this code:

$(\"#test\").siblings(\'p\').remove();
$(\"#test\").remove();

How can I chain this code instead of writing it separately?

7条回答
  •  隐瞒了意图╮
    2020-12-08 13:38

    May be off topic.. you can change the view of the problem:

    $("#test, #test ~ p").remove(); // !! incorrect way, see comment below
    

    Guys sorry :( my decision isn't correct!!

    Selector '~' isn't equal 'sibling'-method. '~' selects all sibling 'p'-elements that follow AFTER the '#test' element.

    So i suggest another decision:

    $("#test, > p", $('#test').parent()).remove();
    

    It is not enough elegant but the most faster way. Please check it 'http://jsperf.com/how-to-chain-this-code-stackoverflow-16009101'

    Performance test result:

    Performance test result

    PS http://jsfiddle.net/Dpe59/

提交回复
热议问题