Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript and the DOM Making Changes to the DOM Get and Set Content with textContent and innerHTML

Eric Wilson
Eric Wilson
9,358 Points

How would you update the Heading with the "Enter" key?

I tried the code below, and I couldn't get it to work. It also made the click event quit working. (And yes, I plan to make a function to update the headline.)

if (headlineInput === document.activeElement) {
  document.addEventListener('keypress', (e) => {
        if (e.key === 'Enter) {
          headline.textContent = headlineInput.value;
          headlineInput.value = '';  
         }
     }
  });
}

2 Answers

Eric Wilson
Eric Wilson
9,358 Points

I was able to figure it out after a little more trial and error. Here is what worked for me:

const headline = document.getElementById('headline');
const updateHeadingBtn = document.getElementById('btn-main');
const headlineInput = document.getElementById('main');

updateHeadingBtn.addEventListener('click', () => {
   headline.textContent = headlineInput.value;
   headlineInput.value = '';
});

headlineInput.addEventListener('keypress', function (event) {
  if (event.key === 'Enter') {
    headline.textContent = headlineInput.value;
    headlineInput.value = '';
  }
});

Try changing document.addEventListener to headline.addEventListener and 'Enter to 'Enter'

Eric Wilson
Eric Wilson
9,358 Points

Thanks for the suggestions! It still isn't working, unfortunately.