What could be causing the error? And is there a way to successfully append the child div to the parent div?

Here is the error message that I am encountering:

Uncaught TypeError: Cannot read property 'appendChild' of null at HTMLButtonElement.<anonymous>

Error is located at app.js on line 7

const flexContainer = document.querySelector('.flex-container')
const btn = document.querySelector('.btn')

btn.addEventListener('click', e => {
  let div = document.createElement('div')
  div.classList.add('.item-1')
  flexContainer.appendChild(div)
})
body{
  background: #333;
  min-height: 100vh;
}

.flexbox-container{
  display: flex;
  justify-content: space-around;
}

.flexbox{
  width: 300px;
  margin: 10px;
  border: 3px solid pink;
  background: white;
}

.item-1{
  min-height: 200px;
}
.item-2{
  min-height: 200px;
  align-self: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Card</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>

  <button class="btn">add card</button>
  <div class="flexbox-container">
    <div class="flexbox item-1"></div>
    <div class="flexbox item-2"></div>
  </div>
  <script src="app.js"></script>
</body>
</html>

Visit the webpage here

Answer №1

The desired class you are searching for is .flex-container, however, it appears that in your HTML code the class is named .flexbox-container. This mismatch is likely causing the variable flexContainer to return null.

Answer №2

Here is a code snippet for creating flexbox items dynamically:

const flexContainer = document.querySelector('.flexbox-container')
const btn = document.querySelector('.btn')

btn.addEventListener('click', e => {
  let div = document.createElement('div')
  div.classList.add('flexbox', 'item-1');
  flexContainer.appendChild(div)
})
body {
  background: #333;
  min-height: 100vh;
}

.flexbox-container {
  display: flex;
  justify-content: space-around;
}

.flexbox {
  width: 300px;
  margin: 10px;
  border: 3px solid pink;
  background: white;
}

.item-1 {
  min-height: 200px;
}

.item-2 {
  min-height: 200px;
  align-self: center;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  <meta name="viewport" content="width=device-width, initial-scale=1.0>
  <title>Card</title>
  <link rel="stylesheet" href="style.css>
</head>

<body>

  <button class="btn>add card</button>
  <div class="flexbox-container>
    <div class="flexbox item-1></div>
    <div class="flexbox item-2></div>
  </div>
  <script src="app.js></script>
</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing dynamic title insertion into a popover element using jQuery

My goal is to assign a title to my popover object in a local project. I have already included the following files: bootstrap.css v4.2.1 jquery.min.js v2.2.0 bootstrap.min.js v4.2.1 popper.min.js v1.11.0 Initially, there was a basic button present. <i ...

Scrolling presentation with dynamic animations

Does anyone have any suggestions for creating a scrolling effect similar to the one on this website? I want to implement a scroll effect where each presentation page is revealed one by one when the user scrolls using their mouse wheel, encouraging them to ...

Include brand logo to the Bootstrap navigation bar

Following the method provided in Bootstrap documentation, I included the following code: <div class="container"> <a class="navbar-brand" href="#"> <img src="/img/hangers.jpg" alt= ...

Nextjs couldn't locate the requested page

After creating a new Next.js application, I haven't made any changes to the code yet. However, when I try to run "npm run dev," it shows me the message "ready started server on [::]:3000, url: http://localhost:3000." But when I attempt to access it, I ...

Tips for converting file byte code to file form data

From one folder I am retrieving a file and uploading it to another server. However, when I extract the file from the first folder, I receive a byte code representation of that file. The API for uploading the file to the second folder requires FormData as a ...

Trouble with Webpack compiling SCSS files

I'm struggling with setting up webpack to bundle my js react components, js modules, and compile my .SCSS files to css. Despite multiple attempts, I keep encountering errors. Below is an excerpt from my webpack.config.js: const webpack = require(&a ...

Error: The value "'827'" cannot be assigned to "Course_Content.course_outline_id" as it must be a valid instance of "Course_Outline"

While working on my django view, I encountered an error stating: ValueError: Cannot assign '827': 'Course_Content.course_outline_id' must be a 'Course_Outline' instance. I attempted to convert it to an int but it still didn&ap ...

Having trouble with the response from the Object object?

Can someone assist me with the response I am getting here? I am receiving a response from an API call and trying to store the results from screen_results. However, when I attempt to print it out, all I see is [Object object]. I have tried to stringify it, ...

I am facing a challenge with AngularJS where I am unable to navigate between pages using the

I'm having issues with my route file app.js. Whenever I click on any link or button, it redirects me to books.html. What could be the mistake I'm making? var myApp = angular.module('myApp', ['ngRoute']); myApp.config([&apo ...

Change the background color of numbers in an array using DOM manipulation in JavaScript

Can someone assist me with the following task: 1. Generate an array containing 10 numbers ranging from 0 to 360. 2. Display these numbers on the DOM within a chosen element. 3. Adjust the background color of each number based on its HUE value in (hue, sat ...

Vue: Child component not rendering string prop

Hey there, I'm currently exploring the ins and outs of Vue and diving into its one-way data bind model, component registration, and passing props. Within my index.js file, I've set up my parent component to render a single child component for no ...

Cannot access PDF files on Android Chrome

I'm using a responsive bootstrap application and encountering an error when trying to open a PDF on mobile. I can open the PDF from my iPhone, but when trying to do so on Android Chrome, I receive a "media not supported exception" message. The applic ...

Is there a way to rotate a div without utilizing the "transform" CSS property?

I am currently utilizing a plugin from the SVG library to render graphics within a div (). However, I am encountering an issue when attempting to rotate it using the "transform" property. The rotation is purely visual and does not alter the X and Y axes of ...

How can one change the color of movable tiles to red while keeping the rest of the tiles in their original state in a puzzle game?

In this section of our code, the function moveTile is responsible for moving a tile. How can I modify it so that the hover color changes to red? function moveTile(identity) { var emptyId = findEmptySpace(); if (isEmptyNeighbor(identity)) { document.ge ...

Difficulty with obtaining .responsetext in AJAX and PHP

On my real estate website, I have a form for users to 'Add a Property'. Although I will implement form validation later on, here is the current html/js code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR ...

Tips for displaying CSS background color on top of an inline style background image

I am facing a dilemma while using Laravel - if I put a background image into my CSS style sheet, I lose my variable. Currently, this is how I have it set up: <div class="gradient"><div class="topback" style="background-image: url('/storage/c ...

A step-by-step guide to displaying API data in a React frontend using functional components

I've managed to create a backend API using Node+Express+MSSQL and tested the routes with POSTMAN. However, I'm facing challenges when trying to display the data on the front-end using React Functional components/hooks. I'm unsure if I'm ...

Is it possible to modify the menu design for a specific page?

Is there a way to customize the appearance of a menu on a specific page of your website? My website's "Main Menu" has 6 menu items, and I'm currently using a menu module called "AS Superfish Menu". This module is set up to make the menu responsi ...

Loading JavaScript on a different page using AJAX is not possible

Why is it that AJAX can load HTML, CSS, PHP, etc., but not JavaScript files when using JavaScript? Does AJAX have limitations in this regard? If so, how would one go about loading another HTML page that contains JavaScript with AJAX? Here's a simple ...

Creating a two-column grid layout using Bootstrap 4 is a simple and efficient process. Let's see how

I've been struggling to get this to display side by side in a two-column grid. Even after following Bootstrap tutorials, I can't seem to make it work. Check out the code below: <div class="row"> <div class="col-md-8 ...