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 trial
Andrew Whatmore
Full Stack JavaScript Techdegree Student 2,256 PointsSolution + Security Q - is it ever OK to use innerHTML or innerAdjacentHTML instead of textContent?
Should I still use textContent even if the values are hard-coded rather than set by user?
Should it still be used in case of a bad actor changing the hard-coded values? Or is innerHTML/innerAdjustedHTML OK for adding hard-coded values to a page? If the latter, should TrustedHTML be used with innerHTML/innerAdjustedHTML?
My solution (excluding the array/object definition part), using textContent again:
// get the main section of the page, which we will add to
let main = document.querySelector('main');
// function to create the elements needed for each object
function makeElements() {
let elements = ['h2', 'h3', 'p', 'img'];
for (let i = 0; i < elements.length; i++) {
elements[i] = document.createElement(elements[i]);
}
return elements;
}
// loop through each object in the pets array
for (let x = 0; x < pets.length; x++) {
// create a new elements array using function
let pageElements = makeElements();
// for each object, set the content of the elements to the property values that we want
pageElements[0].textContent = pets[x].name;
pageElements[1].textContent = `${pets[x].type} | ${pets[x].breed}`;
pageElements[2].textContent = `Age: ${pets[x].age}`;
pageElements[3].src = pets[x].photo;
pageElements[3].alt = pets[x].breed;
// add the elements to the page using a loop
for (let y = 0; y < pageElements.length; y++) {
main.appendChild(pageElements[y]);
}
}
1 Answer
Steven Parker
243,318 PointsIf the content has no HTML tags, it makes sense to always write it into textContent.
However, if HTML is needed, I would feel confident writing into InnerHTML as long as the content was either hard-coded or constructed without including any user input.