user2918741
user2918741

Reputation: 87

alternative for .attr() in javascript

$(this).attr('id':'name', visibility:'hidden', fill:'black', stroke-width:2)

used this approach for 1000 element to set their attribute. All working fine, but .attr() takes 10ms to execute, I need to optimize it, is there any alternative for .attr().

Thanks in advance

Upvotes: 3

Views: 9182

Answers (3)

Stu Blair
Stu Blair

Reputation: 1343

Rather than changing attributes directly, why not add a class to those elements that is defined to have the attributes you want?

I ran a performance test here: http://jsperf.com/attr-vs-classsname And the attr() method was 33% slower on my browser/OS.

Here's how:

javascript:

this.className = "custom-class";
this.id = 'name';

accompanying css:

.custom-class {
  visiblity: hidden;
  fill: black;
  stroke-width: 2;
}

Also, you're missing the brackets in your attr() call, and the hyphenated stroke-width method needs to be put in quotes, like this:

$(this).attr({id:'name', visibility:'hidden', fill:'black', 'stroke-width':2});

Upvotes: 2

kavun
kavun

Reputation: 3381

The fastest alternative would be to set the corresponding property of an attribute directly.

this.id = 'name';
this.style.visibility = 'hidden';

http://jsperf.com/jquery-attr-vs-setattribute/2

Upvotes: 2

rajesh kakawat
rajesh kakawat

Reputation: 10896

try something like this,For better performance use setAttribute().

The setAttribute() method adds the specified attribute, and gives it the specified value.

this.setAttribute("id","name");
this.style.visibility =  'hidden';

Upvotes: 3

Related Questions