Kamil T
Kamil T

Reputation: 2216

Can't convert HTMLImageElement to string?

I'm using javascript to reach img elements nested in some <div>.After that I want to add those images to a string variable.

I wrote that:

var SomeVariable="";
$("myDivId img").each(function(){
  console.log(this);
  SomeVariable += this;
});
console.log(SomeVariable);

When console.log is used in .each function, it shows something like:

<img (some elements)>, which is exactly what I want.

When I use console.log at the end, to write whole value, it says:

[object HTMLImageElement][object HTMLImageElement]

I tried to use some conversion, but I don't really know how to get to it.

Upvotes: 2

Views: 8474

Answers (1)

alex
alex

Reputation: 490637

Assuming you want the string representation of their HTML...

var html = $("myDivId img").clone().appendTo("<div />").html();

If you're only supporting browsers which have the outerHTML property.

var html = $("myDivId img")
           .map(function() { return this.outerHTML; }).get().join("");

The reason you get "[object HTMLImageElement]" is because an Object's toString() will give you "[object x]", where x is the [[Class]] (an internal property) of the object.

Upvotes: 7

Related Questions