JavaScript JavaScript and the DOM 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
203,736 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.