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 ?

0

2 Answers 2

3

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.
Sign up to request clarification or add additional context in comments.

5 Comments

do you have a source for that quote?
@GeorgeMauer which one?
The block that you indented - the formatting is similar to a quotation. Did you not mean to imply that it was one?
@GeorgeMauer Here From w3Schools At the middle of th page.
Just did some formatting for you. For your performance testing I recommend creating a jsperf 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.
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.

3 Comments

For onclick, which method is good ? image.onclick or image.setAttribute('onclick','') ?
Because, onclick is an event unlike src, using inline methods have certain disadvantages as describe in above link.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.