it’s my first time posting a question here, sorry if I say something strange. I am currently studying Javascript. I just tried to create a function that has 3 arguments, a Parent element, the element to be created, and the text or content that will go inside it. The text is added just fine but the second argument which is meant for creating the element doesn’t seem to be working.
Here is the function I tried to create
const newFirstChild = function(el,newEl,elContent){
const selectElement = (parentElement) => document.querySelector(el);
const newElement = (createElement) => document.createElement(newEl);
newEl = newEl.innerText = elContent;
selectElement(el,newEl).prepend(newEl);
}
I wanted to make something like: the function will get the Parent element, the element to be added, and the content that will go inside. I tried to add a new bolded text for example, the text is added but is not bolded.
Did I do something wrong? Or is it not possible to do this at all?
2
Answers
Changed a few things according to the answer, and it ended up like this:
I called the function like this:
newFirstChild('p','b','sample text')
It adds a new bold text as a child of the paragraphThere are a lot of things going on in the function you posted that are wrong or just don’t make sense.
For example, you created a function called
newElement
that never gets called:Another question is, why do you need to create a new element when you already have a reference to the new element? If you have a reference to it, then it’s already been created. Perhaps you are trying to copy the element that
newEl
points to?In your question, is
newEl
a string? If so, then you can create the new element with the following function:You can call it like this: