1

if I use:

<a class="btn btn-primary someClassName">Test</> 
$(document).ready(function () {
    $("document").on("click", '.someClassName', function () {
        alert('click');       
    });
});

If I click the link, it doesn't do anything.

However, if I change it to:

<a class="btn btn-primary someClassName">Test</> 
$(body).ready(function () {
    $("document").on("click", '.someClassName', function () {
        alert('click');       
    });
});

Then the alert is displayed.

So my question is: why does $("document").on() not work, and why does $("body").on() work?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
L-Four
  • 13,345
  • 9
  • 65
  • 109
  • because 'document' is not HTML element whereas 'body' is..! – Sudhir Bastakoti Dec 01 '14 at 10:09
  • you can view detailed statement about it here http://www.sitepoint.com/jquery-body-on-document-on/ – Sarath Dec 01 '14 at 10:10
  • Possible duplicate of http://stackoverflow.com/questions/12307112/difference-between-document-body-and-body-jquery – Sudharsan S Dec 01 '14 at 10:10
  • This question is not a duplicate, but the answer is indeed found in https://stackoverflow.com/questions/12307112/difference-between-document-body-and-body-jquery. Thanks for the answers, it was indeed something I simply looked over :) – L-Four Dec 01 '14 at 10:19

2 Answers2

7

This is because when you pass a string to the selector jQuery uses the sizzle selector engine to search for that element within the DOM. So you are looking for a <document /> element, which obviously will not exist.

The correct syntax is to use $(document); note the lack of quotes. jQuery then uses the document object as the parent selector.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
4

'document' is a element selector, and there is no element with tagname document

$(document)
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531