Error occurs when attempting to change the color of a dynamically generated div, resulting in the message: "Type Error: Unable to assign a value to the property '

I'm facing an issue with my code where I have a parent div that loads with a random color, and upon clicking a button, it should create a new colored div inside. However, I keep encountering the following error:

TypeError: Cannot set property 'background' of undefined

Even though when I console.log the newly created leaf, it shows up as a node rather than undefined. How can I resolve this error and successfully add a random color to the leaf? Below is the snippet of my code:

<template>
  <div id="parent-branch">
    <h1>Branch (B 0) (L 0) {{mycolor}}</h1>
    <div class="button-container">
      <button>Add Branch</button>
      <button @click="addLeaf">Add Leaf</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
      return {
        mycolor: '#'+(Math.random()*0xFFFFFF<<0).toString(16)
      }
  },
    mounted() {
     document.getElementById('parent-branch').style.background = this.mycolor;
  },
    methods: {
     colorGenerator() {
        this.mycolor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
        document.getElementById('parent-branch').style.background = this.mycolor;
       },

     addLeaf() {
      var div = document.createElement('div');
      div.className = 'leaf'
      var leaf = document.querySelectorAll('.leaf');
      leaf.style.background = this.mycolor;
      var container = document.getElementById('parent-branch');
      container.appendChild(div)

     },
    },
  name: 'ParentBranch',
}
</script>

<style scoped>
.parent-branch {
    width: 100%;
    height: 100px;
}
</style>

Answer №1

When utilizing the document.querySelectorAll function, it retrieves an array of elements. To modify the background style of each element, you need to iterate through all the elements.

Therefore, the addLeaf method should be updated as follows:

addLeaf() {
      var div = document.createElement('div');
      div.className = 'leaf'
      var leaf = document.querySelectorAll('.leaf');
      leaf.forEach(l => l.style.background = this.mycolor)
      var container = document.getElementById('parent-branch');
      container.appendChild(div)
    },

Although unrelated to your query, it is worth noting that when creating branches and leaves, they may appear empty if no content is added to them despite being appended to the DOM.

I have made a modification to addLeaf by inserting some text:

addLeaf() {
      var div = document.createElement('div');
      div.className = 'leaf'
      div.innerText = "hi"
      var leaf = document.querySelectorAll('.leaf');
      leaf.forEach(l => l.style.background = this.mycolor)
      var container = document.getElementById('parent-branch');
      container.appendChild(div)
    },

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

Use a JavaScript function on identical IDs

Can someone please help me figure out how to hide multiple divs with the same id using JavaScript? I attempted the following: <script> function filterfunc() { if(document.getElementById('filter_deductible').value == 'id_50'){ ...

We encountered an error while trying to locate the 'socket.io' view in the views directory

Having an issue with my nodejs server. Check out the code below: server.js global.jQuery = global.$ = require('jquery'); var express = require('express'), path = require('path'), menu = require("./routes/menu"); var ...

Obtain the CSRF token from a webpage using JavaScript

I am currently working on a project where I need to retrieve the csrf token from a web page built with Django using javascript. The structure of my HTML template is as follows: <div class = "debugging"> <p id = "csrf">{% csrf_token %}</p ...

Efficiently managing multiple database updates with PHP and JQuery

Having trouble processing multiple mySQL updates simultaneously? I have 4 select/option boxes fetching data from a db table and I want to update the database onChange using JQuery. It's working with one select module, but adding more causes issues. Th ...

The Angular bootstrap datetimepicker doesn't support disabling past dates

Has anyone successfully disabled past dates on an angular bootstrap datetimepicker before? I've tried using the date-disabled attribute, but I can't seem to get it to work. <datetimepicker class="calendar-format" data-ng-model ...

When creating nested objects, the defineproperty function on the object prototype does not trigger

Exploring and experimenting to unravel the workings of this feature, but I find myself puzzled by this particular scenario. Object.defineProperty(Object.prototype, 'a', {set: function() {console.log("Set!");} }); Based on my understanding, when ...

`Some Items Missing from Responsive Navigation Menu`

Hey there! I'm currently diving into the world of responsive design and I'm attempting to create a navigation bar that transforms into a menu when viewed on a mobile device or phone. Everything seems to be working fine, except that not all the na ...

Upon invoking the useEffect function, the default value can be seamlessly established within the input field of the antd library

I have a function called loadProfile that I need to execute within the useEffect hook. When this function is triggered, I want the name Mario to be automatically displayed in the input field labeled name. How can I set this default value using the antd lib ...

Display with organized information, Arrange with unprocessed data in DataTables.net

Below is a snippet of the datatables configuration I am working with: { "dom" : "rltip", "processing" : true, "serverSide" : false, "order" : [ [ 1 , "desc" ] ], "searching" : false, data: [ { "column-a" : "Samp ...

Modifying browser.location.href Cancels AJAX Requests

I am facing an issue with my HTML page. I have a button that, when clicked by the user, updates the window.location.href to the URL of a text file. In order to ensure that the file is downloaded and not opened in the browser, the text file is served with C ...

I am receiving all NFT IDs when I should only be getting the ones that are associated with the current account

I am facing an issue where I am receiving all NFTs token IDs instead of just the one that belongs to the current account. The code snippet causing this problem is as follows: const { enableWeb3, account, isWeb3Enabled, Moralis, deactivateWeb3 } = useMorali ...

Tips for setting up Highcharts tooltip.headerFormat using the function getDate() plus 5

I'm facing a little challenge trying to understand how the JavaScript function getDate interacts with Highcharts datetime on xAxis. My goal is to show two dates in the tooltip header, forming a date range like this: 1960/1/1 - 1965/1/1. The first da ...

What is the method for creating an array of strings in VueJS?

In my VueJS and Vuetify project, I am working on creating a modal that allows users to input strings into a text field. What I aim to achieve is adding the inputted string to an array when the user clicks on create button. For example, if I enter 'inp ...

How can strings of dates be arranged in MM/DD/YYYY order?

Is there a correct way to sort these dates in descending order? I've attempted using arr.sort() and arr.sort().reverse(), searched extensively on stack overflow, but still cannot find a solution. Every attempt at sorting them seems to be incorrect. [ ...

What is the best way to customize the appearance of Image tags located inside SVGs, whether they are in separate files or embedded within the code

I am developing a custom SVG editor application and facing an issue with implementing a highlighted effect when an <image> element is clicked. I have successfully accomplished this for other elements like <circle> by adjusting attributes such a ...

Retrieve the thousand separator for numbers using Angular in various languages

When using the English locale, numbers appear as follows: 111,111,222.00, with a comma as the thousand separator and a point as the decimal separator. In languages like German, the same number would be represented as 111.111.222,00, reversing the positions ...

Can someone assist me with troubleshooting my issue of using a for loop to iterate through an array during a function call

Having recently delved into the world of Javascript, I've encountered a challenging problem that has consumed my entire day. Despite attempting to resolve it on my own, I find myself feeling quite stuck. The structure of my code is relatively simple ...

Several conditional statements in JSX

In my JSX Return() code, I am encountering an "If" issue when one of my conditions has 2 different 'onClick' events. There are 2 'a' tags, where one will display button 'X' if a statement is true and the other will display but ...

Removing jQuery error label from an HTML block

I need a single command that will remove an error label from my HTML when the field content is changed. It currently works on input and select elements, but not within an input-group. I am looking for a solution that will work universally across all instan ...

Interactive input values linked to other variables

I need to dynamically adjust the value ****here**** of the input with the id="inputWorkload" based on the value of inputDuration (newTask.duration * 2) Is there a way to achieve this using Vue.js? <div class="col-sm-2"> <div class="form-grou ...