-1

I have created an array of objects and a function that loops over this array while creating a component, I am trying to append the component to a div in the HTML but I keep getting the following error: app.js:722 Uncaught TypeError: Cannot read property 'append' of null

Also is there a way to append the 'method' component to a different div?

Can anyone help? I would like to know how to do this in vanilla Javascript.

let internationalCountries = [
    {
        name: "Hermes",
        method: "Standard Delivery",
        timmeScale: "Delivery within 5 to 7 working days",
    },
    {
        name: "USP",
        method: "Standard Delivery",
        timmeScale: "Delivery within 1 to 2 working days",
    },
    {
        name: "DPD",
        method: "Standard Delivery",
        timmeScale: "Delivery within 11 to 21 working days",
    },
]

let renderCountryList = () => {
    let itemName = "";
    let method = "";
    
    for (let i = 0; i < internationalCountries.length; i++){
        itemName += '<li class="country">'+ internationalCountries[i].name +'</li>';
        method += '<div class="delivery-info"> <p>' + internationalCountries[i].method + '</p> <p>' + internationalCountries[i].timmeScale + '</p> </div>';
    }
    return itemName, method;
    
}
renderCountryList()

let list = document.querySelector('.country-list')
let countryList = renderCountryList();
console.log(countryList)
list.append(countryList)
<div>
   <ul class="country-list">
                                
   </ul>
</div>
RMP1992
  • 49
  • 4

1 Answers1

0

Are you executing your javascript before your HTML? Typically you'll get this error if the element has not been rendered yet.

Try putting your javascript at the end of your HTML file after the various elements.

codedude
  • 5,577
  • 13
  • 54
  • 86
  • As you can see, if you run the code its actually displaying the html tags and it seems to be compressed, how do i fix that? – RMP1992 Mar 24 '21 at 00:48
  • @RMP1992 in your for loop, you're currently just creating a string (even though that string looks like HTML elements.) You need to use DOM tags like [createElement()](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement) to build your HTML elements and then use something appendChild() to add them to your parent element. – codedude Mar 24 '21 at 01:08