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 JavaScript and the DOM (Retiring) Making Changes to the DOM Styling Elements

Selecting an element and its id with querySelector?

Is it acceptable/make sense to use querySelector to select an element as well as its id (e.g. a button with the id "toggleList)? I was able to get the code below to work but we haven't learned anything about it so far...I thought this might make the code clearer since there are multiple buttons.

const toggleButton = document.querySelector('button#toggleList');
const toggleList = document.querySelector('.list'); 

const input = document.querySelector('input.description');
const p = document.querySelector('p.description');
const button = document.querySelector('button.description');

toggleButton.addEventListener('click', () => {
    if (toggleList.style.display == 'none') {
      toggleButton.textContent = 'Hide List';
      toggleList.style.display = 'block';
    } else {
      toggleButton.textContent = 'Show List';
      toggleList.style.display = 'none';
    }
});

button.addEventListener('click', () => {
  p.innerHTML = input.value + ':';

});

1 Answer

Steven Parker
Steven Parker
231,271 Points

The tag name "button" isn't needed, since element ID's must be unique on the page.

And "querySelector('#toggleList')" will give you the exact same result as "getElementById('toggleList')", so either one will do the job for this exercise.