SivaRajini
SivaRajini

Reputation: 7375

Javascript setAttribute Vs jquery multiple attribute setter

I want to set so many attributes for multiple elements. Javascript always give better performance when comparing to jquery.

i want to know which one gives better performance when settling multiple attributes via jquery and javascript.

Jquery multiple attribute setter:

$(element).attr({'id': 'id1', 'index':1, 'value':10,'check':'checked'});

using javascript setAttribute :

element.setAttribute('id','id1');
element.setAttribute('index','1');
..................................

when am using javascript i need to write multiple lines. otherwise need to create custom function for this.

can anyone explain which one gives better performance ? and why ?

Thanks,

Siva

Upvotes: 4

Views: 3353

Answers (4)

Krasimir
Krasimir

Reputation: 13529

Here is a jsperf which tests setting of attributes. I'm not sure that it covers your situation but as the others said - pure javascript is a lot faster then using a library. (I'm not even sure that the jsperf is a valid one. I mean if it test what you need).

http://jsperf.com/aaa-setting-attribute

jQuery version is 66% slower then the pure javascript variant.

Upvotes: 3

Ringo
Ringo

Reputation: 3965

jQuery is a library, so I think it better than pure javascript. It help you to use javascript easier. I supposed that! You can see the same question here

If you want to get all of attributes of element, you can see here also.

Upvotes: -1

RobG
RobG

Reputation: 147383

You should probably be setting properties, not attributes, as they are more consistent across browsers and have a more consistent effect on DOM elements (sometimes setting an attribute affects the property, sometimes it doesn't). Setting the property nearly always has the desired affect (e.g. setting a checkbox to checked), setting the related attribute doesn't always.

You can also use a small function if you want to set multiple properties on an element:

function setProperties(element, props) {
  for (var prop in props) {
    if (props.hasOwnProperty(prop)) {
      element[prop] = props[prop];
    }
  }
}

I can't see that it would be any slower than jQuery.

Upvotes: 1

Sergio
Sergio

Reputation: 6948

Computers cost much less than programmers.

Let's say:

Using pure js will make code run for 1ms, and programmer work 3 hours.

Using jQuery will make code run for 2ms and programmer work 1 minute

See profit?

Upvotes: 1

Related Questions