In a javascript file I create a variable
let containerCart = document.getElementsByClassName('contPRS');
and aside I have a function where I store in an object some values obtained from the id of an element and then I create another variable and in this after creating an element and putting a few lines of html using .innerHTML() as described later in the code
const row = document.createElement('div');
row.classList.add('product');
row.innerHTML =
`<div class="imagen">
<img src="${image}" alt="${name}">
</div>
<div class="info">
<h4 id="nombrePR">${name}</h4>
</div>
<div class="eliminar">
<i class="icon-trash-empty" data-cod="${cod}"></i>
</div>`;
I try to add an appendChild to the containerCart variable and in the console when I run the script it sends me a message TypeError: Cannot read properties of undefined (reading 'appendChild')
and in another web page it tells me that a solution can be accessing the containerCart in position 0 to be able to use the .appendChild
, that is, containerBuyCart[0].appendChild(row);
; I already tried it and in the same way I got the same TypeError mentioned. In another section it tells me to make a conditional to validate that the value is an object and that it contains the appendChild property before calling the method, which left me without understanding the solution that it wants to show because the variable that is related to getElementsByClassName()
it gives a value of null to then perform the conditional.
the link of the page where I found everything mentioned above is: https://bobbyhadz.com/blog/javascript-typeerror-appendchild-is-not-a-function#:~:text=The%20%22appendChild%20is% 20not%20a,misspelling%20appendChild%20%2D%20it's%20case%20sensitive .
and the image of the last solution is:
Can someone help me understand this part or if you have another solution for this type of error that you can share with me, I thank you in advance
document.getElementsByClassName() returns an HTML collection and you can't directly manipulate it, that's why you have to access each element by its index, and since you're getting only one, the index is zero:
[0]
If it didn't work for you, the collection is probably empty because an element with the specified class was not found.
Now, if you have only one container, you can get it with document.querySelector() , which returns only one element that matches the specified selector.
#
to start.
to the beginning