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.

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay