GemmaJ
GemmaJ

Reputation: 41

Why is [object HTMLCollection] being displayed instead of the element I created?

In Javascript I am attempting to make a new div. This is what I added to make the div.

html+= "<div>" + concerts + "</div>";

but in my browser it displays [object HTMLCollection] where the div tag should be.

concerts is a pre defined var.

Can anyone explain to me what I might be missing to make this work. Thanks in advance.

Upvotes: 2

Views: 13005

Answers (3)

wiredolphin
wiredolphin

Reputation: 1641

Using += you are adding an object, seemingly a collection of elements, to a string, causing the implicit call to its toString() method. So you get [object HTMLCollection].

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074285

concerts is apparently a collection of elements, such as the one you get from getElementsByTagName and similar. When you do

"<div>" + concerts + "</div>"

...you implicitly call toString on it, and so you get that "[object HTMLElementCollection]" string.

If you want to put all the elements in the collection in a div, and then add that div to the page, you can't use string concat:

var div = document.createElement('div');
Array.prototype.slice.call(concerts).forEach(concerts, function(concert) {
    div.appendChild(concert);
});
document.body.appendChild(div); // Or wherever you want to add the div

The Array.prototype.slice.call(concerts) part of that converts the HTMLElementCollection into a true array, then we use forEach on that array to loop through and move the elemnts in to the div. (This answer goes into that in more detail.) (We need the slice part of that, because HTMLElementCollections are typically live collections, and so moving the first element into the div takes it out of the collection, which messes up the forEach.)

This example starts out with four paragraphs that aren't in a div. Then when you press the button, it creates a div with padding and a border, and moves the paragraphs into it:

document.querySelector("button").onclick = function() {
    var concerts = document.getElementsByTagName("p");
    var div = document.createElement('div');
    div.className = "foo";
    Array.prototype.slice.call(concerts).forEach(function(concert) {
        div.appendChild(concert);
    });
    document.body.appendChild(div); // Or wherever you want to add the div
};
.foo {
  border: 1px solid black;
  padding: 4px;
}
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
<button type="button">Click me</button>

Upvotes: 5

Tyler McGinnis
Tyler McGinnis

Reputation: 35276

html must be an object. When you try to add something to an object it turns it into a string making it look like [object]. You probably don't want to just += but instead use a method on the DOM api to insert concerts (appendChild for example could work if you made some changes)

Upvotes: 0

Related Questions