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 badges1 Answer
Reset to default 13The 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
版权声明:本文标题:javascript - QuerySelector is not recognising #id with space - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741224863a2361667.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论