I'm dynamically creating and rendering div tag using a JS class, like this:
class CreateNote {
constructor(title, body) {
this.title = title;
this.body = body;
this.render = () => {
// Create div 1 & 2 and give them the same class name
const div1 = document.createElement('div');
div1.className = 'notes-inner-container';
const div2 = document.createElement('div');
div2.className = 'notes-prev';
const hr = document.createElement('hr');
hr.className = 'notes__line';
// Nest 'div2' inside 'div1'
div1.appendChild(div2);
div1.appendChild(hr);
/*
Create Paragraph 1 & 2 and give them the same
class name and some text
*/
const p1 = document.createElement('p');
p1.innerText = this.title;
const p2 = document.createElement('p');
p2.className = 'notes-prev__body';
p2.innerText = this.body;
// Nest p 1 & 2 inside 'div2'
div2.appendChild(p1);
div2.appendChild(p2);
// Get the body tag and append everything
const notesDiv = document.querySelector('.notes');
notesDiv.appendChild(div1);
}
}
}
I need to add an event listener to this div. But as it takes some time for this div to actually get rendered, when I try to attach the listener to it, it keeps returning a null value. The solution I found for this issue is if I add the event listener inside my render method, like this:
// Previous chunk of code
const div1 = document.createElement('div');
div1.className = 'notes-inner-container';
div1.addEventListener('click', () => {
// Do something;
}
// Next chunk of code
And then I was wondering, is this a bad practice? If so, which way would you do it? If you need more information please let me know and thanks in advance.
rendera normal method not an arrow function created in the constructor, but apart from that everything is fine with the code.