How to append element, BEFORE the firstChild of a certain container?

As a beginner, I would appreciate your take on what’s wrong with my code. Several times I tried to check and change what’s wrong.

My aim is to append newHeading, before the firstChild of a certain section:

let hasClass = body.classList.contains("blog");
if (hasClass == true) {

let contentArea = document.querySelector("#main");
let newHeading = document.createElement("h1");
newHeading.className = "contentArea";

contentArea.appendChild(newHeading);
newHeading.innerHTML = "הבלוג שלנו";
Node.insertBefore(contentArea.firstChild, newHeading);

}

Can you show us the section of HTML you’re trying to insert the new heading into?

insertBefore() is not a static method of the Node interface, but a regular method that is applied to the parent element of the element where the new element should be inserted before.

additionally, the argument sequence is wrong (https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore) and your insertion logic as well (you’re trying to insert the new element twice).

Yes but would like to avoid that at least for now.

I tried to read in MDN before publishing the question here but didn’t understand the Node-based terminology there.

Regarding my code:

Node.insertBefore(contentArea.firstChild, newHeading);

I think I now understand the logic mistake I had there — I was trying to add the newHeading as the first child before the first child, and it should be just added as the first child and that’s it.

That worked for me:

parentNode.insertBefore(<myNewElement>, parentNode.firstChild);

I must say in a glimpse it looks a bit wired but I now understand the logic, which I describe as:

insert (something) before, in the context of parentNode. While, by the argument, it will be before its firstChild.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.