Difference between $(document.body) and $('body')

前端 未结 6 1566
傲寒
傲寒 2020-12-13 11:48

I am a jQuery beginner and while going through some code examples I found:

$(document.body) and $(\'body\')

Is there any difference

6条回答
  •  粉色の甜心
    2020-12-13 12:16

    The answers here are not actually completely correct. Close, but there's an edge case.

    The difference is that $('body') actually selects the element by the tag name, whereas document.body references the direct object on the document.

    That means if you (or a rogue script) overwrites the document.body element (shame!) $('body') will still work, but $(document.body) will not. So by definition they're not equivalent.

    I'd venture to guess there are other edge cases (such as globally id'ed elements in IE) that would also trigger what amounts to an overwritten body element on the document object, and the same situation would apply.

提交回复
热议问题