<div id="addHere"></div>
const arr = [1,2,3];
function addToElem(elem, data) {
const elemInDom = document.querySelector(elem);
if (!elemInDom) return;
data.forEach(item => {
const div = document.createElement('div');
div.innerHTML = item;
elemInDom.append(div);
})
}
addToElem('#ddHere', arr);
вариант с string interpolation:
const arr = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 3, name: 'three'}];
function createWonderfullP(data) {
return `
<p class="wonderfull-p">
${data.name}: <span>${data.id}</span>
</p>
`
}
function addToElem(elem, data) {
const elemInDom = document.querySelector(elem);
if (!elemInDom) {
console.error('No such target element')
return;
};
data.forEach(item => {
const div = document.createElement('div');
div.innerHTML = createWonderfullP(item);
elemInDom.append(div);
})
}
addToElem('#addHere', arr);
а теперь немного функциональной магии:
const arr = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 3, name: 'three'}];
const createWonderfullP = (data) => `
<p class="woderfull-p">
${data.name}: <span>${data.id}</span>
</p>
`;
const createDivWithContent = (content) => {
const div = document.createElement('div');
div.innerHTML = content;
return div;
}
const getInserter = (parent) => (elem) => parent.append(elem);
function addToElem(elem, data) {
const elemInDOM = document.querySelector(elem);
if (!elemInDOM) {
console.error('No such target element')
return;
};
const insertInElemInDom = getInserter(elemInDOM);
data
.map(createWonderfullP)
.map(createDivWithContent)
.forEach(insertInElemInDom)
}
addToElem('#addHere', arr);