skip to Main Content
  var cell = $("<div></div>");
  for (var j  =0 ; j < items.paths.length ;j++){
     cell.append(item.paths[j]);
   }
      
  $(`<tr><td style="white-space: normal;">
     ${cell}
   </td></tr>`).appendTo('#mytable');

I made the dom object named cell

And I want to deploy the cell to html, however it shows only [object Object], where am I wrong?

2

Answers


  1. If you are appending htmlStrings then do it all at once and then use .join(', ') to convert the array into a string (no iteration needed).

    const items = {
      paths: ["North", "East", "West", "South"]
    };
    
    $(`<tr>
         <td style="white-space: normal;">
           <div>${items.paths.join(', ')}</div>
         </td>
       </tr>`).appendTo('table');
    table, td {border:1px solid black}
    <table></table>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    Login or Signup to reply.
  2. Any object, when coerced into a string will output as [object Object]. Your cell variable is an object.

    Either build a string or don’t; you’re mixing the two.

    You have a number of options:

    • You can build the string in one go (other answer, not repeated here)
    • Build cell as a string rather than a dom object, eg
    var cell = "<div>";
    for (var j  =0 ; j < items.paths.length ;j++){
      cell += items.paths[j];
    }
    cell += "</div">
    

    though if doing that then use .join()

    var cell = "<div>" + items.paths.join(" ") + "</div>";
    
    • You could convert the cell to a string, eg
    $(`<tr><td>${cell.html()}</td></tr>`)
    

    note: this will remove the outer <div></div>, so maybe ${cell[0].outerHTML}

    • or you can use DOM manipulation to add the cell content
    $("<tr><td></td></tr>").appendTo("#tbl").find("td").append(cell);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search