2

HTML

       <h1>Javascript Playground</h1>

        <div id="first"></div>
        <div id="second"></div>

    </body>

I need to insert a table into the div with this information, including columns for code, title and offering without touching the HTML (only using JavaScript)

let units = [
    {
        'code': 'COMP2110',
        'title': 'Web Technology', 
        'offering': 'S1'
    },  
    {
        'code': 'COMP2010',
        'title': 'Algorithms and Data Structures', 
        'offering': 'S1'
    },

]

1 Answer 1

1

Probably you can start like the following:

let units = [{'code': 'COMP2110', 'title': 'Web Technology', 'offering': 'S1'}, {'code': 'COMP2010', 'title': 'Algorithms and Data Structures', 'offering': 'S1' } ];

// find your div first
const div = document.getElementById('first');

// building the HTML for the div
let html = `<table>
     <thead>
         <tr>
           ${Object.keys(units[0]).map(e => `<th>${e}</th>`).join('')}
         </tr>
     </thead>`

html += `<tbody>`;
units.forEach(e => html += `<tr>
      ${Object.values(e).map(v => `<td>${v}</td>`).join('')}
</tr>`);

html += `</tbody></table>`;

// adding HTML to your div
div.innerHTML = html;
table, th, td {
  border: 1px solid black;
}
<h1>Javascript Playground</h1>

<div id="first"></div>
<div id="second"></div>

I hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.