0d: 00h: 00m: 00s

🎁 Get 3 extra months of learning — completely FREE

That's 90 extra days to master new skills, build more projects, and land your dream job.

Become a PRO
Background Image

🎁 Get 3 extra months of learning completely FREE

Become a PRO
Kamohelo Nthoesane
PRO
last month
Kamohelocountry asked

What does Uncaught TypeError: Cannot set the properties of undefined (setting 'textContent') mean?

Abhay Jajodia
Expert
2 days ago
Abhay Jajodia answered

Hi Kamohelo,

That error usually means you're trying to update something that doesn't exist in the DOM at the moment you're accessing it. In this case, you're trying to set the textContent of an element, but the variable holding that element is actually undefined.

This often happens when you're using something like element.children[2], but there are fewer than 3 children, so JavaScript can't find the item at index 2. Then, when you try to set textContent, it throws the error because you’re basically saying undefined.textContent = ..., which isn't valid.

Let’s say your code looks like this:

const priceList = document.querySelector("#price-list");
const update = document.querySelector("#update");

update.addEventListener("click", () => {
    const thirdItem = priceList.children[2];
    const thirdItemPrice = thirdItem.children[0];
    thirdItemPrice.textContent = "$4.00";
});

If thirdItem doesn’t exist, or if it doesn’t have a child at index 0, you’ll get that exact error.

To avoid it, you can add checks:

if (thirdItem && thirdItem.children.length > 0) {
    const thirdItemPrice = thirdItem.children[0];
    if (thirdItemPrice) {
        thirdItemPrice.textContent = "$4.00";
    } else {
        console.error("The child element you're trying to access doesn't exist.");
    }
} else {
    console.error("The third list item or its children do not exist.");
}

Also, using console.log() is super helpful — it lets you see what each variable actually holds before using it. That way, you can catch undefined values early and avoid these errors.

If you have more questions, I am here to help.

This question was asked as part of the JavaScript in Browser course.