Skip to main content

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

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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…

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:

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Get practical advice to start your career in programming!


Master complex transitions, transformations and animations in CSS!