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>