admin管理员组

文章数量:1295862

I'm just starting with JQuery and am working through a tutorial vid. At one point the presenters go for javascript instead of a JQuery selector. Just wondering why the javascript getElementById below works fine when passing an object to a function, but the second one doesn't?

Thanks!

// works
addTask(document.getElementById('taskText'), evt);

// doesn't
addTask($('#taskText'), evt);

I'm just starting with JQuery and am working through a tutorial vid. At one point the presenters go for javascript instead of a JQuery selector. Just wondering why the javascript getElementById below works fine when passing an object to a function, but the second one doesn't?

Thanks!

// works
addTask(document.getElementById('taskText'), evt);

// doesn't
addTask($('#taskText'), evt);
Share Improve this question asked Aug 12, 2011 at 4:42 GlinkotGlinkot 2,97411 gold badges45 silver badges67 bronze badges 3
  • Now we need to guess what's in the addTask, right? – zerkms Commented Aug 12, 2011 at 4:45
  • My thought was that it didn't make a difference - it accepts an object and an event. I could post it though. – Glinkot Commented Aug 12, 2011 at 4:59
  • obviously if your function does accept one object and doesn't accept another - then issue is with the function ;-) – zerkms Commented Aug 12, 2011 at 5:19
Add a ment  | 

5 Answers 5

Reset to default 9

getElementById() returns a DOM element reference.

jQuery's selector returns a jQuery object. You can get the element reference from the jQuery object using

$('#taskText').get(0);

See http://api.jquery./get/

To add to the other answer, regarding the result, if you want to use jQuery (which is easier to read), you can get the dom node directly like so:

addTask($('#taskText')[0], evt);

$('#taskText') returns a jQuery object reference.

document.getElementById('taskText') returns a DOM element reference.

If your addTask() function doesn't know how to convert them to what it needs, then that would be the issue since one of them will need a conversion.

If you want to get the first DOM element reference from the jQuery object, you can do so with this:

$('#taskText').get(0)

So these two should be identical:

$('#taskText').get(0)
document.getElementById('taskText')

Both are not exactly same

document.getElementById('taskText'); //returns a HTML DOM Object

var contents = $('#taskText');  //returns a jQuery Object

var contents = $('#taskText')[0]; //returns a HTML DOM Object

so you have to change it to get HTML Dom Object

addTask($('#taskText')[0], evt);

As @Phil and @jfriend00 have pointed out, document.getElementById('taskText') is a DOM element, and $('#taskText') is a jQuery object. The latter is an object of all DOM elements that match the selector.

Think of it as a zero based array, you could pass in the DOM element by doing this:

addTask($('#taskText')[0], evt);

本文标签: javascriptJQuery select by ID vs documentGetElementByIDStack Overflow