Cannot read properties of undefined.

Hello 👋 So I'm trying to create a class for an alert card. And now whenever i try to use the class methods it throws an error saying Cannot read properties of undefined ( reading 'classList') What am I missing here?
6 Replies
~MARSMAN~
~MARSMAN~•2y ago
~MARSMAN~
~MARSMAN~•2y ago
And this is the error. I don't understand why when i console log the whole object it displays it with its every property. But when i use any of the class methods it says the element is undefined. I also tried to change the object class from outside of the Class by accessing the properties. and it throws the same error. So what am I missing here?
MarkBoots
MarkBoots•2y ago
when you create a card instance, you'll have to store it in a variable to be able to get access to it's methods and properties outside the class Also, a good practice is to name classes this a captital letter
const card = new AlterCard(alterItem)
card.showCard()
card.writeAlertContent()
const card = new AlterCard(alterItem)
card.showCard()
card.writeAlertContent()
also, if you want to access methods outside the class, they can not be static or private there were some other issues as well
class AlertCard {
constructor(selector) {
this.alertItem = document.querySelector(selector);
this.alertContent = this.alertItem.querySelector("#alert-content");
this.alertAnchor = this.alertItem.querySelector("#alert-anchor");
this.closeBtn = this.alertItem.querySelector("#close-alert");
}
showCard() {
this.alertItem.classList.add("show");
}
writeAlertContent(content) {
this.alertContent.innerText = content;
}
}

const card = new AlertCard("#alert");
card.showCard();
card.writeAlertContent("working");
class AlertCard {
constructor(selector) {
this.alertItem = document.querySelector(selector);
this.alertContent = this.alertItem.querySelector("#alert-content");
this.alertAnchor = this.alertItem.querySelector("#alert-anchor");
this.closeBtn = this.alertItem.querySelector("#close-alert");
}
showCard() {
this.alertItem.classList.add("show");
}
writeAlertContent(content) {
this.alertContent.innerText = content;
}
}

const card = new AlertCard("#alert");
card.showCard();
card.writeAlertContent("working");
i made it a bit cleaner by passing the id selector into the constructor function, so you dont have to select it first inside the constructor we select the element and the other parts you need
~MARSMAN~
~MARSMAN~•2y ago
Thank you so much Mark! It's working now 🙌 And thanks for the Tips!😊
MarkBoots
MarkBoots•2y ago
no problem. good luck!
Want results from more Discord servers?
Add your server