Search code examples
javascripthtmlqueryselector

querySelector is unable to access passed id


<div id="page1">
               block1
        </div>
        <div id="page2">
             block2
        </div>
        <div id="page3">
            block3
        </div>

I am trying to access the id of the div by using following function, but it does not work.

           function  aa(page)
              {
                  document.querySelector('#${page}').style.display='block';
              }

I am getting the following error: 'querySelector' on 'Document': '#${page}' is not a valid selector.


Solution

  • You need to use template literals enclosed by backticks instead of single quotes which delimit a normal string.

    document.querySelector(`#${page}`)