Adding HTML using Javascript issue


I have a HTML list:

<!DOCTYPE html>
        <script type="text/javascript" src="js/script.js"></script>
        <link rel="stylesheet" href="style.css" type="text/css" />
        <h1>Homework 4</h1>
        <div id="text-box">
            <section class="text-area" > 
                <ul style="list-style-type:none">
                    <li>Name: Ana Pop</li>
                    <li>Age: 25</li>
                    <li>CNP: 123456789123</li>
                    <li>Address: 156 Muzicii Street</li>
                        <ul style="list-style-type:none">
                        <li>Clementina Pop Age: 50</li>
                        <li>George Pop Age: 50</li>

I want to add a new HTML element using Javascript with the following code:

     var list = document.getElementById('text-box'); = 'text-box-new';

    for (var i = 0; i< users.length; i++) {
        console.log("Name " ,users[i].name);
        console.log("Age ", users[i].age);
        console.log("CNP ", users[i].cnp);
        console.log("Address", users[i].address);
        console.log("Parents", users[i].parents);
        var item = document.createElement('section');
        item.className = 'text-area';
        item.innerHTML = '<li>'  + users[i].name + '</li><li>' +  users[i].age +  '</li><li>' + users[i].cnp + '</li><li>' + users[i].address + '</li><li>' + users[i].parents + '</li>';  

The code is running but is displaying only the numbers and instead of letters i get:
[object Object]


[object Object]
[object Object]
[object Object],[object Object]

Any ideea how I can solve this?

Hi marianureche,

There is a modification required for one of the lines in javascript code. As per the users object, name contains 2 parts “first name” and “lastname” , but in javascript you have just used “users[i].name”. since users[i].name is a dictionary value with 2 items in it, it displays as [object object] .

Please replace your javascript code line with below. It will work fine. I have just pasted the 3 lines of javascript.

 var item = document.createElement('section');
 item.className = 'text-area';
 item.innerHTML = '<ul style="list-style-type:none"><li>Name: ' + users[i].name.firstName + ' ' + users[i].name.lastName + '</li><li>Age: ' + users[i].age + '</li><li>CNP: ' + users[i].cnp + '</li><li>Address: ' + users[i].address.number + ' ' + users[i].address.street + '</li><li>Parents: <ul style="list-style-type:none"><li>' + users[i].parents[0].name + ' Age:' + users[i].parents[0].age  + '</li><li>'+ users[i].parents[1].name + ' Age:' + users[i].parents[1].age + '</li></ul></li></ul>';

Thanks and Regards,

1 Like

Hey, Thank you Navya. It’s working.
Thank’s for clarifying that for me too.