admin管理员组

文章数量:1278690

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?

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?

Share Improve this question asked Aug 23, 2020 at 20:58 HardRockHardRock 1,0912 gold badges17 silver badges42 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

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.

本文标签: javascriptQuerySelector is not recognising id with spaceStack Overflow