开发者

Why wrap a DOM element in jQuery if doesn't simplify things? (Example from jQuery Cookbook)

开发者 https://www.devze.com 2023-02-21 05:24 出处:网络
I came across this example in the O\'Reilly jQuery Cookbook (recipe 3.1): var urls = []; $(\"div#post a[href]\").each(function(i){

I came across this example in the O'Reilly jQuery Cookbook (recipe 3.1):

var urls = [];
$("div#post a[href]").each(function(i){
    urls[i] = $(this).attr('href');
});
alert(urls.join(","));

I understand that $().each(fn) runs the function in the context of the DOM element selected. What I don't understand is: Why wrap the DOM element in a jQuery object?

It seems to me like 开发者_如何转开发urls[i] = this.href; would have been the more straightforward approach here.

  • Is it a best practice to always wrap DOM elements in jQuery before touching them?
  • Or is the author doing this simply to show us that it can be done?
  • Or is it done for some other reason altogether?


One of jQuery's primary goals is to act as a consistent layer between the programmer and the potentially unpredictable browser-defined functions. So yes, it is generally best practice to use the jQuery wrappings to any DOM functions.


Typically I try to do all JavaScript in native JavaScript and use jQuery where appropriate. That being said, if you don't wrap the DOM element in the jQuery object then you won't be able to access the jQuery methods.


Wrapping with jQuery Object allows for chaining with other jQuery functions. jQuery main purpose is to achieve cross browser compatibility. It also simplifies the way we work with JavaScript.

Ex: $('#id').attr(...).css(...).delay().fadeIn().fadeOut().remove().... and so on. It would take many lines of code, time and effort to write this with plain Javascript, and not to mention maintaining browser compatibility.

0

精彩评论

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