最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can't convert HTMLImageElement to string? - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Oct 16, 2012 at 11:40 dandan78 13.9k13 gold badges67 silver badges81 bronze badges asked Oct 16, 2012 at 11:34 Kamil TKamil T 2,2161 gold badge19 silver badges27 bronze badges 2
  • 1 Do you want the string representation of their HTML? – alex Commented Oct 16, 2012 at 11:37
  • DOM elements are not HTML. The console just represents them with HTML syntax for visual purposes. The correct toString() value of the element is [object HTMLImageElement]. – I Hate Lazy Commented Oct 16, 2012 at 11:43
Add a ment  | 

1 Answer 1

Reset to default 7

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.

发布评论

评论列表(0)

  1. 暂无评论