Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select an element by ID with jQuery using regex?

People also ask

How do you select element by id in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

How do I select something in jQuery?

The select() method is an inbuilt method in jQuery which is used when some letters or words are selected (or marked) in a text area or a text field. Syntax: $(selector). select(function);

What is jQuery regex?

It's used to match strings or parts of strings and for search and replace operations. jQuery uses regular expressions extensively for such diverse applications as parsing selector expressions, determining the type of browser in use, and trimming whitespace from text.

Can you use CSS selectors in jQuery for selecting elements?

jQuery uses CSS selector to select elements using CSS. Let us see an example to return a style property on the first matched element. The css( name ) method returns a style property on the first matched element.


You can combine both selectors in a multiple attribute selector.

​$("[id^=AAA_][id$=_BBB]")

It will return all the elements that matches all the specified attribute filters:

  • [id^=AAA_] matches elements with id attribute starting with AAA_, and
  • [id$=_BBB] matches elements with id attribute ending with _BBB.

Another generic alternatives:

  • Using a custom :regex() selector,
  • Using a .filter()-based approach.

Use this:

$('[id^="AAA_"][id$="_BBB"]')

Fiddle: http://jsfiddle.net/J6hGx/


You can look for id's starting with AAA and ending with BBB like this:

​$("[id^=AAA_][id$=_BBB]")

The working fiddle: http://jsfiddle.net/DN9uV/


This can be done like so:

$('input').filter(function(){ return this.id.match(/^AAA_.+_BBB$/) })

You can give use $('input', <context>) to make the search more precise. See also here