221B
221B

Reputation: 851

What is the difference between <img> tag and new Image().src?

Is there any specific reason we use new Image().src=URL instead of <img> URL </img>. I see this kind of usage mostly in web tracking or some image pixels etc. would appreciate your help.

Upvotes: 1

Views: 2365

Answers (2)

6502
6502

Reputation: 114481

You can create DOM nodes mainly in two ways:

  • You put them in the HTML using tags like <img src="foo.jpg">
  • You create them dynamically from Javascript using for example document.createElement

If the nodes are fixed then static creation is better because allows a designer to create and edit a page directly without having to know Javascript. If however they're created dynamically depending on the user actions on the page then you cannot place them in the HTML and you're forced to use Javascript.

Somethings you may need to just act on an existing DOM element and you may see code like

<img id="pic" src="foo.jpg">

in the HTML (note the id= part)

and then you can access it from code using for example

document.getElementById("pic").src = "bar.jpg";

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

This is because the img tag has an attribute called src. The HTML in your second example is invalid.

Upvotes: 0

Related Questions