$(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
$(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
Share Improve this question asked Nov 13, 2013 at 6:01 user2918741user2918741 871 silver badge10 bronze badges 3- 1 if you need such performance , use pure js instead. – Royi Namir Commented Nov 13, 2013 at 6:04
- 3 That doesn't look live valid syntax. – elclanrs Commented Nov 13, 2013 at 6:05
-
Caching
$(this)
to a variable would save a lot of msecs. – Teemu Commented Nov 13, 2013 at 6:39
3 Answers
Reset to default 3try 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';
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./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';
acpanying 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});
The fastest alternative would be to set the corresponding property of an attribute directly.
this.id = 'name';
this.style.visibility = 'hidden';
http://jsperf./jquery-attr-vs-setattribute/2