Detect if a jQuery object is on the page or not

前端 未结 4 1592
温柔的废话
温柔的废话 2021-01-07 18:11

Given a jQuery object, $j, I need to know if it represents something that is already on the page or if it is something that has not yet been put on the page. Fo

4条回答
  •  独厮守ぢ
    2021-01-07 18:41

    With jQuery (at least with version 1.7.1) $('html').parent() returns a non-empty array ([#document]):

    $j = $("

    I'll cook you some eggs, Margie.

    "); $j.parent().length === 0 $('html').parent().length === 1 $('body').parent().length === 1

    So 'mu is too short''s note is not an issue:

    I can see the first one failing if $j is the html or possibly body; I'm happy to ignore those two pathological cases. I can't think of any way that the second approach would fail.

提交回复
热议问题