开发者

JQuery select by ID vs document.GetElementByID

开发者 https://www.devze.com 2023-03-27 08:11 出处:网络
I\'m just starting with JQuery and am working through a tutorial vid.At one point the presenters go for javascript instead of 开发者_StackOverflow中文版a JQuery selector.Just wondering why the javascr

I'm just starting with JQuery and am working through a tutorial vid. At one point the presenters go for javascript instead of 开发者_StackOverflow中文版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);


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.com/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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号