0

I am trying to create a netflix type effect with CSS and JavaScript where things are displayed on a carousel using flexbox and trying to add the flex item into the container with JavaScript as am using an API to get data so never know how many elements there will be but nothing it working with the JavaScript.

const container = document.getElementById("container");
var newDiv = document.createElement("div");
newDiv.className = "item";
var arr = ["1","1","1"];

const map = arr.map(x => {return `<div>${x}</div>`});
console.log(map)
map.forEach(function(element){
    newDiv.innerHTML = element;
    container.append(newDiv)
});

The container has the class container and the extra divs have the class items

Here is the HTML:

<body>
    <!--Title for the Page-->
    <h1 id="title">Will and Amys Movie App</h1>

    <!--Grid Layout-->
    <div id="container">
        <div class="item"></div>
    </div>
</body>
Uncaught TypeError: container is null
    <anonymous> file:///D:/Github/MovieSummerProject22/script.js:8
    <anonymous> file:///D:/Github/MovieSummerProject22/script.js:4
script.js:8:5
    <anonymous> file:///D:/Github/MovieSummerProject22/script.js:8
    map self-hosted:180
    <anonymous> file:///D:/Github/MovieSummerProject22/script.js:4

1 Answer 1

1

change your newDiv.innerHTML = element; to newDiv.innerHTML += element;

Also this can be improved a bit and you can use only the map, no need to loop twice

Note that you are creating an extra div, that you don't want.

const container = document.getElementById("container");
const arr = ["1", "1", "1"];

arr.map(x => {
  const newDiv = document.createElement("div");
  newDiv.className = "item";
  newDiv.innerHTML += x;
  container.append(newDiv)
});
<div id="container"></div>

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

19 Comments

it still says that the container is null thought?
I don't see it in your question, your question is about am using an API to get data so never know how many elements there will be but nothing it working with the JS., so it is about the elements. Also did you see my snippet w/ improved code?
Yeah so i am using the array as the data so far and yeah I changed the code to do this and it still days null and not adding anything to the screen
container being null means that your selector doesn't exist in your html, in my snippet exists and it works, do you have this <div id="container"></div> ?
<body> <!--Title for the Page--> <h1 id="title">Will and Amys Movie App</h1> <!--Grid Layout--> <div id="container"> <div class="item"></div> </div> </body> that is everything in my body
|

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.