Create a jQuery function with custom paragraph-text

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:

    <span class="instagram">@instagram</span>
    <span class="twitter">@twitter</span>
    <span class="github">@github</span>

Answers 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.

Related Articles