I have written this function for creating complete HTML-elements including arbitrary attributes and inner HTML.
I want to keep and reuse it. Therefore I have tried to document the usage well.
I would be interested in hints concerning:
Could the code be improved? So that it is becomes more succinct and efficient?
Can one expect the function to work as intended even when it isn't used correctly?
Is the documentation understandable? Or does it have to be improved?
Is there a way to check if a valid HTML node name has be assigned as first parameter? Currently I'm only checking if the parameter has been assigned and is of type string.
/**
* Returns an HTML-element of the specified node type,
* with the specified attributes and text.
*
* @param { string } nodeName - E.g. 'div', 'li', 'p'
* @param { string } attrs - The attributes of the
* HTML-element. Each attribute has to be defined
* as <name>=<value>. Multiple attributes have to
* be separated with a blank between each pair.
* Example:
* 'value=12 class=option-item data-test=123Demo'
* @param { string } innerHtml - String for the
* innerHTML of the HTML element.
*
* @return { Object } - The created HTML element.
* @throws { Object } - In case of error.
*
* Usage example:
* wrap.appendChild( getHtmlElement(
'div',
'class=spec data-shipping=express id=123',
'Your package will be shipped soon.' ));
*/
function getHtmlElement(nodeName, attrs, innerHtml) {
var ret = null;
if (!nodeName || typeof nodeName !== 'string') {
throw { message: 'No nodeName-parameter assigned.' }
}
attrs = attrs || '';
innerHtml = innerHtml || '';
ret = document.createElement(nodeName);
attrs = attrs.split(/\s/g);
if (attrs[0]) {
attrs.forEach(function(attr) {
attr = attr.split(/=/);
if (attr[1]) {
ret.setAttribute(attr[0], attr[1]);
}
});
}
ret.innerHTML = innerHtml;
return ret;
}
// Usage-example:
document.body
.appendChild(getHtmlElement(
'p',
'class=inserted-paragraph data-info=paragraph-number-one',
'Lorem ipsum <i>dolor</i> sit amet, <b>consectetuer</b> ' +
'adipiscing elit. Aenean <u>commodo</u> ligula eget dolor.'));
document.body.insertAdjacentHTML('beforeend', '<p class=....>.......</p>')
on multiple lines for the same readability? \$\endgroup\$