I do know how to check if a property exists (hasOwnProperty
, in
, !== undefined
, etc).
But I don’t know how to avoid to perform an action on this property if it doesn’t exist.
Is there a solution to avoid the if
(property && action
in my case) verification each time ?
Similar question : Javascript – how to avoid multiple if condition checks when checking if object has a property? Not really relevant in my case
const myFunction1 = myFunction2 = () => {};
const generateElement = (p) => {
let div = document.createElement(p.tag);
p.classes && (div.className = p.classes);
p.style && (div.style.cssText = p.style);
p.content && (div.innerHTML = p.content);
p.appendIn && p.appendIn.appendChild(div);
p.attribs && Object.entries(p.attribs).forEach((y) => {
div.setAttribute(y[0], y[1]);
});
p.events && Object.entries(p.events).forEach((y) => {
div.addEventListener(y[0], y[1], false);
});
return div
}
var newElem = generateElement({
tag: 'div',
classes: 'mydiv',
id: 'id42',
content: 'Hello world!',
style: 'background:#ccc',
attribs: {
'tabindex': 0,
'title': 'Title #1'
},
events: {
'click': myFunction1,
'mouseout': myFunction2
},
appendIn: document.body
});