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 (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
217,640 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.