DEV Community

_Khojiakbar_
_Khojiakbar_

Posted on

Reusable createElement()

Function Explanation

The createElement function creates a new HTML element with optional classes and content.

Parameters

tagName: The type of element you want to create (e.g., 'div', 'h1').
classList: (Optional) A string of classes you want to add to the element.
content: (Optional) The inner HTML content you want to add inside the element.

Steps

  1. It creates a new element of the type specified by tagName.
  2. If classList is provided, it sets the element's class attribute.
  3. If content is provided, it sets the element's inner HTML content.
  4. It returns the created element.
function createElement(tagName, classList, content) {
    // Create an element of type tagName
    const tag = document.createElement(tagName);

    // If classList is provided, set the class attribute
    if (classList) tag.setAttribute('class', classList);

    // If content is provided, set the inner HTML
    if (content) tag.innerHTML = content;

    // Return the created element
    return tag;
}

// Example usage
console.log(createElement('h1', 'bg-success p-3', 'Hello world')); 
// Output: <h1 class="bg-success p-3">Hello world</h1>

console.log(createElement('div')); 
// Output: <div></div>
Enter fullscreen mode Exit fullscreen mode

In the examples:

  • The first call creates an <h1> element with the classes bg-success and p-3, and the content "Hello world".
  • The second call creates an empty <div> element with no classes or content.

Top comments (0)