skip to Main Content

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


  1. Chosen as BEST ANSWER

    Changed a few things according to the answer, and it ended up like this:

        const newFirstChild = function(el,newEl,elContent){
            const parentElement = document.querySelector(el);
            const child = document.createElement(newEl);
            child.innerText = elContent;
            parentElement.prepend(child);
        }
    

    I called the function like this: newFirstChild('p','b','sample text') It adds a new bold text as a child of the paragraph


  2. There 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:

    const newElement = (createElement) => document.createElement(newEl);
    

    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:

    function myFunction(parent, childType, text){
        const child = document.createElement(childType);
        parent.prepend(child);
        child.innerText = text;
    }
    

    You can call it like this:

    myFunction(document.getElementById("parentElem"), "div", "hello world");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search