function createAndAppendElement(parentId, tagName, textContent, attributes = {}) { const parentElement = document.getElementById(parentId); if (!parentElement) { console.error(`Parent element with ID '${parentId}' not found.`); return null; } const newElement = document.createElement(tagName); newElement.textContent = textContent; for (const key in attributes) { if (attributes.hasOwnProperty(key)) { newElement.setAttribute(key, attributes[key]); } } parentElement.appendChild(newElement); return newElement; } // Example usage: //
const listItem = createAndAppendElement('container', 'li', 'New List Item', { 'data-id': 'item-1', class: 'my-item' }); if (listItem) { console.log('Element created and appended:', listItem); }