1

Example:

function getNewElement(elementName, elementClass) {
    return $('<p>')
        .addClass(elementClass)
        .text(elementName);
}

And then i can reuse it like:

const paragraph = getNewElement('test', 'some-class');
const paragraphSecond = getNewElement('test2', 'some-class2');

Is there any way to run the code or any similar approach ? Thanks

3 Answers 3

5

The 0th item in a jQuery object is the native DOM Element object. As such just add [0] to the return statement in your function to get your desired output:

function getNewElement(elementName, elementClass) {
  return $('<p>').addClass(elementClass).text(elementName)[0];
}

const paragraph = getNewElement('test', 'some-class');
console.dir(paragraph);

const paragraphSecond = getNewElement('test2', 'some-class2');
console.dir(paragraphSecond);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

That being said, there's nothing inherently wrong with returning a jQuery object from the function which will stop it from being re-used. Any problem would only come from how you use the result of the function in later logic.

Sign up to request clarification or add additional context in comments.

Comments

1

you could create the element using the following approach:

function getNewElement(elementName, elementClass) {
    return $(document.createElement("p"))
        .addClass(elementClass)
        .text(elementName)
        .get(0);
}

2 Comments

oh sorry, I misread the title.. I have updated with the correct code
$(document.createElement("p")) seems superfluous
0

The function below generates a tag and returns it:

function getNewElement(elementName, elementClass, tagName = "p") {
  return $('<'+tagName+'>').addClass(elementClass).text(elementName)[0];
}

1 Comment

Note that in the case of the OP this would return a <test> or <test2> element, not a <p> element

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.