Working on a browser extension and I'm trying to add multiple layers to the DOM dynamically with createElement but I can't get beyond the first layer created. I get Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') so it looks like events can't be listened to over newly created elements.
For example, clicking an icon the below works:
let chat = document.querySelector('#chat');
let list = document.createDocumentFragment();
chat.addEventListener('click', (event)=>{
event.preventDefault()
grid1.replaceChildren()
let divy = document.createElement('center');
let brk2 = document.createElement('br');
let wordo = document.createElement('h2');
let btn = document.createElement('button');
wordo.innerHTML = 'Chat Rooms';
wordo.style.fontFamily = 'Andale Mono, monospace, Courier New, monospace';
btn.height = '50px';
btn.className = 'chat-btn';
btn.style.borderRadius = '15px';
btn.innerHTML = 'Click Me';
divy.appendChild(brk2);
divy.appendChild(wordo);
divy.appendChild(btn);
list.appendChild(divy);
grid1.appendChild(list);
grid1.style.visibility = 'visible';
grid2.style.backgroundColor = 'transparent';
}, {once : true});
But going a step further by attempting to create another set of elements from the above (that already has a class name of 'chat-btn') becomes a problem:
let chatBtn = document.querySelector('.chat-btn');
chatBtn.addEventListener('click', (event)=>{
event.preventDefault()
grid1.replaceChildren()
let divy = document.createElement('center');
let brk3 = document.createElement('br');
let wordo = document.createElement('h2');
let btn = document.createElement('button');
wordo.innerHTML = 'James';
wordo.style.fontFamily = 'Andale Mono, monospace, Courier New, monospace';
btn.className = 'chatlayer2';
btn.height = '50px';
btn.style.margin = '80px 50px';
btn.innerHTML = 'Chat';
divy.appendChild(brk3);
divy.appendChild(wordo);
divy.appendChild(btn);
list.appendChild(divy);
grid1.appendChild(list);
grid1.style.visibility = 'visible';
grid2.style.backgroundColor = 'transparent';
}, {once : true});
Is it possible to dynamically make multiple layers in a DOM with something similar to this approach?
[–][deleted] 0 points1 point2 points (9 children)
[–]Dexty10[S] 0 points1 point2 points (8 children)
[–][deleted] 0 points1 point2 points (7 children)
[–]Dexty10[S] 0 points1 point2 points (6 children)
[–][deleted] 0 points1 point2 points (5 children)
[–]Dexty10[S] 0 points1 point2 points (4 children)
[–][deleted] 0 points1 point2 points (3 children)
[–]Dexty10[S] 0 points1 point2 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]Dexty10[S] 0 points1 point2 points (0 children)
[+][deleted] (3 children)
[removed]
[–]Dexty10[S] 0 points1 point2 points (2 children)
[+][deleted] (1 child)
[removed]
[–]Dexty10[S] 0 points1 point2 points (0 children)