Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialsanjeshwari Nand
Full Stack JavaScript Techdegree Student 4,673 PointscreateElement function- help
i have created multiple properties for some elements eg for the edit and remove button, i have both the textContent property and the className property. with the eg in the video ie creating a second function createElement, how do i do that for a) multiple(2) properties and b) do i need to create separate createElement functions for those elements that only have 1 property and those that have multiple ??
1 Answer
Robert Manolis
Treehouse Guest TeacherHi Sanjeshwari, it's totally possible to do all that in a single function with the use of conditionals and loops. That's beauty of code. I wrote up a short example of one way to go about this. Check it out.
const createEl = (el, parent, attras = {}, text) => {
// Create new element
const newEl = document.createElement(el);
// If attras parameter contains attributes and values, loop over them and them to new element
if (Object.keys(attras).length) {
for (let key in attras) {
newEl.setAttribute(key, attras[key]);
}
}
// If text parameter is included, add text to element
if (text) {
newEl.textContent = text;
}
// append new element to parent
return parent.appendChild(newEl);
}
const body = document.querySelector('body');
createEl('p', body, {class: "myClass", id: "myId"}, 'Test');
The above code can be dropped into any client side JS file hooked up to some HTML, and it will add the following HTML to the DOM just before the closing body tag: <p class="myClass" id="myId">Test</p>
.
Hope that helps!
sanjeshwari Nand
Full Stack JavaScript Techdegree Student 4,673 Pointssanjeshwari Nand
Full Stack JavaScript Techdegree Student 4,673 Pointsthank you so much Robert! that was very helpful ! :)