Categories
JavaScript Answers

How to call getElementById based on a partial string with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *