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

JavaScript

jason limmm
jason limmm
8,009 Points

adding html entities into text nodes using js

plus.addEventListener("click",()=>numbers.textContent+="+");

minus.addEventListener("click",()=>numbers.textContent+="-");

multiply.addEventListener("click",()=>numbers.textContent+="&times");

division.addEventListener("click",()=>numbers.textContent+="&#247");

i want to add the multiplication and division symbol using entities but i tried this one and it doesn't work, it returns "&times" and "&#247" respectively if i click either buttons

right now i am not able to get any snapshots of my project

1 Answer

Steven Parker
Steven Parker
231,248 Points

Remember that "textContent" is always taken verbatim. What you're adding is HTML code. So do this instead:

plus.addEventListener("click", () => (numbers.innerHTML += "+"));
minus.addEventListener("click", () => (numbers.innerHTML += "−"));
multiply.addEventListener("click", () => (numbers.innerHTML += "×"));
division.addEventListener("click", () => (numbers.innerHTML += "÷"));

Also:

  • the entity codes always begin with "&" and end with ";"
  • + and − typically look nicer (and match the others better) than ordinary "+" and "-"
  • ÷ is also a named entity code

And finally, another approach would be to just use the unicode characters directly as the textContent:

plus.addEventListener("click", () => (numbers.textContent += "+"));
minus.addEventListener("click", () => (numbers.textContent += "−"));
multiply.addEventListener("click", () => (numbers.textContent += "×"));
division.addEventListener("click", () => (numbers.textContent += "÷"));