jquery filtering has + not

前端 未结 5 455
离开以前
离开以前 2020-12-01 04:41

Okay I have list items, some have a span, some not.
On my event I want to add the span when they don\'t have any yet.

has() works fine, but

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 04:55

    The accepted answer works well, if you don't want to filter out only those elements which do have the spans as direct children.

    As the :has() and the .has() loop over all descendants, not just the children.

    In that case, you have to use a function

    $("li").not(function() {
        // returns true for those elements with at least one span as child element
        return $(this).children('span').length > 0 
    }).each(function() { /* ... */ })
    

提交回复
热议问题