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
- It creates a new element of the type specified by tagName.
- If classList is provided, it sets the element's class attribute.
- If content is provided, it sets the element's inner HTML content.
- 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>
In the examples:
- The first call creates an
<h1>
element with the classesbg-success
andp-3
, and the content "Hello world". - The second call creates an empty
<div>
element with no classes or content.
Top comments (0)