QuerySelector is not recognising #id with space

Viewed 1340

I am using querySelector to fetch div in order to scroll on that position.

const anchor = document.querySelector('#' + i) 
 if (anchor) {
      anchor.scrollIntoView(true);
      window.scrollBy(0, -190); 
    }

The problem is that in some divs I have id with space e.g Vegan Pizza (variable i) and in this case variable anchor is null and scrolling is not working.

Anyone has idea how to make querySelector working with id with spaces?

1 Answers

The space is the descendant selector. For example:

#container div

will select a div which has an ancestor with an id of container somewhere, like the div below:

<section id="container">
  <div></div>
</section>

Use [id="some id with spaces"] instead:

const anchor = document.querySelector('[id="' + i + '"]') ;

You can also use getElementById:

console.log(
  document.getElementById('some id with spaces')
);
<div id="some id with spaces"></div>

But it would be better to avoid putting spaces in IDs - even if browsers can recognize it (using this workaround), it's not technically valid. Consider either removing all the spaces from the IDs, or putting the values into a different attribute (like the dataset) instead.

Related