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

11,187

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>
Share:
11,187

Related videos on Youtube

GemmaJ
Author by

GemmaJ

Updated on June 04, 2022

Comments

  • GemmaJ
    GemmaJ over 1 year

    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.

    • Quentin
      Quentin almost 8 years
      Because you have a collection of DOM nodes, not a string of HTML.
  • GemmaJ
    GemmaJ almost 8 years
    I tried this but I still got [object HTMLCollection] in my browser
  • GemmaJ
    GemmaJ almost 8 years
    Thanks for the help, I couldn't get this to work with my code unfortunately
  • T.J. Crowder
    T.J. Crowder almost 8 years
    @GemmaJ: If you can't get it working with your code, boil that attempt down to an MCVE (ideally using Stack Snippets -- the <> button -- so it's runnable) and post it as a question. Good luck.