1

How can I create a function out of this? Im using append & prepend to assign elements, would like to keep this as DRY as possible and be able to customize each output text.

let $paragraph = $('<p>', {
    'class': 'my-class',
    text: 'some-text'
});

let $paragraph2 = $('<p>', {
    'class': 'my-other-class',
    text: 'some-other-text'
});

My goal is to be have a easy setup for outputing codeblocks like:

<p>
    Instagram
    <span class="instagram">@instagram</span>
    Twitter
    <span class="twitter">@twitter</span>
    Github
    <span class="github">@github</span>
</p>

1 Answer 1

1

Accept the class and text as parameters:

function createParagraph(cls, text) {
    return $('<p>', {
        'class': cls,
        text: text
    });
}

let $paragraph = createParagraph('my-class', 'some-text');
let $paragraph2 = createParagraph('my-other-class', 'some-other-text');

FWIW, createParagraph as an arrow function:

const createParagraph = (cls, text) => $('<p>', {
    'class': cls,
    text: text
});

I see you're using let, so assuming an ES2015+ browser. If so, you can safely leave the quotes off class in the object initializer. Keywords have been valid in that context since ES5. Of course, if you're transpiling for older JavaScript engines, you'll want to keep it in quotes.

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

Comments

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.