JavaScript
Article
By Sam Deering

jQuery Speed Test: $(this).attr(“id”); vs this.id

By Sam Deering
Last chance to win! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

Leading on from Speed Test $(this) vs .get() vs .eq() I decided to do a quick test to compare the speed of $(this).attr(“id”); vs this.id which can be used on native attributes such as id, src, href, style etc… but not on properties such as bgcolor, data, etc…

--ADVERTISEMENT--

Background

Within context this changes but generally:

$(this) is a jQuery Object which has access to all the jQuery API
this is a reference to the DOM element

Use $(this) for DOM elements that have no yet been created.

Speed

this without the jQuery wrapper is slightly faster on the whole.

$(this).attr(“id”): 42ms
this.id: 1ms

View results: https://jsfiddle.net/jquery4u/F9rP7/

Further reading:

Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?