Sometimes, we want to call getElementById based on a partial string with JavaScript.
In this article, we’ll look at how to call getElementById based on a partial string with JavaScript.
How to call getElementById based on a partial string with JavaScript?
To call getElementById based on a partial string with JavaScript, we call querySelector instead of getElementById.
For instance, we write
const id = document.querySelector('[id^="poll-"]').id;
to call querySelector with '[id^="poll-"]' to match the first element where its ID starts with poll-.
Conclusion
To call getElementById based on a partial string with JavaScript, we call querySelector instead of getElementById.