How to call getelementbyid based on a partial String with JavaScript?

Estimated read time 2 min read

To call getElementById based on a partial string in JavaScript, you can use the querySelector method and a CSS attribute substring matching selector. Here’s an example:

const element = document.querySelector('[id*="partialString"]');

In this example, the querySelector method is called on the document object, and the argument is a CSS attribute substring matching selector. The selector uses the *= operator to match any element whose id attribute contains the partialString substring.

This will return the first element in the document that matches the selector. If there are multiple elements with matching id attributes, only the first one will be returned.

Alternatively, if you know the element tag name, you can specify it in the selector to narrow down the search. For example:

const element = document.querySelector('input[id*="partialString"]');

In this example, the selector matches only input elements whose id attribute contains the partialString substring.

Note that using querySelector with a substring matching selector is less efficient than using getElementById with a full id string, since it involves searching the entire document for matching elements. If possible, it’s best to use getElementById directly, or to assign a specific class to the elements you want to select and use getElementsByClassName instead.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply