0

Is there any difference between the below two methods

var image = document.createElement("img");
1) image.setAttribute('src','mySrc');
2) image.src = 'mySrc';

For any html element, is there a difference in setting some attribute in the above ways ? Is there any browser dependability ?

Raheeb M
  • 505
  • 2
  • 5
  • 13

2 Answers2

2

With setAttribute() you can add an attribute even if it doesn't exist. But it's supported only on major browsers. Ie8 and earlier doesn't support this function.

From w3schools

You should use the attribute when it exists.

The performance of setAttribute is worse

I tested 100 image elements.

  • Running a function that changes the src it took 2 ms.
  • Using setAttribute took 4 ms.
George Mauer
  • 117,483
  • 131
  • 382
  • 612
Dvir
  • 3,287
  • 1
  • 21
  • 33
  • do you have a source for that quote? – George Mauer Oct 20 '13 at 14:13
  • @GeorgeMauer which one? – Dvir Oct 20 '13 at 14:26
  • The block that you indented - the formatting is similar to a quotation. Did you not mean to imply that it was one? – George Mauer Oct 20 '13 at 14:32
  • @GeorgeMauer [Here From w3Schools](http://www.w3schools.com/jsref/met_element_setattribute.asp) At the middle of th page. – Dvir Oct 20 '13 at 14:40
  • Just did some formatting for you. For your performance testing I recommend creating a [jsperf](http://jsperf.com) and getting times of at least a couple hundred ms. Rendering frames ideally takes 16ms so a difference of anything less than that can just depend on when you ran the test. – George Mauer Oct 20 '13 at 14:51
1

2nd method can be used only if the attribute is already available where as 1st Method will create it and assign the value in case if it is not available.

For the image.src, both will work as 'src' attribute is available by default.

Kaf
  • 33,101
  • 7
  • 58
  • 78
  • For onclick, which method is good ? image.onclick or image.setAttribute('onclick','') ? – Raheeb M Oct 19 '13 at 07:46
  • @RaheebM check these links for image.onClick http://www.javascripter.net/faq/addeventlistenerattachevent.htm and http://stackoverflow.com/questions/95731/why-does-an-onclick-property-set-with-setattribute-fail-to-work-in-ie – exexzian Oct 19 '13 at 07:49
  • Because, onclick is an event unlike src, using inline methods have certain disadvantages as describe in above link. – Kaf Oct 19 '13 at 08:03