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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay