Search for items with dynamic id

I want to create a generic function in jquery to select all functions. I have a tab on my web page.

Id of my component: tabId: someDynamicId: rowId: componentId where, someDynamicId is dynamically generated.

So, in jquery I want to find an element whose id starts with - tabId: someDynamicId and ends with the component. And, tabId, someDynamicId and componentId will be passed as an argument to the generic function where this element needs to be found.

+8
jquery jquery-selectors primefaces
source share
3 answers

It's simple:

$('[id^=tabId][id$=componentId]').each(function(){ var id = $(this).attr('id'); // tabId:someDynamicId:rowId:componentId​ var list = id.split(':');​​ console.log(list[0]); // tabId console.log(list[1]); // someDynamicId console.log(list[2]); // rowId console.log(list[3]); // componentId​ }) 

Wildcards in jQuery selectors

But I recommend using the right tools for this job. IDs are useful for finding a specific item, but in your case it is better to use one or two classes and data attributes. For example:

 <div class="tabs" data-component-id="x" data-tab-id="y"> 

Then find all the elements of $ ('. Tabs') and use $ (this) .data ('component-id') and $ (this) .data ('tab-id')

 $('.tabs').each(function(){ var component_id = $(this).data('component-id'); var tab_id = $(this).data('tab-id'); }); 

Update:

An example of using this function:

 function(tabId,componentId) { $('[id^='+tabId+'][id$='+componentId+']').each(function(){ var id = $(this).attr('id'); // tabId:someDynamicId:rowId:componentId​ var list = id.split(':');​​ console.log(list[0]); // tabId console.log(list[1]); // someDynamicId console.log(list[2]); // rowId console.log(list[3]); // componentId​ }) } 
+8
source share

You can do this with regular expressions and filter() . Something like this should work. In this particular example, an identifier is considered starting with "one", followed by a number and ending with "two". Example http://jsfiddle.net/5eXm4/ .

 $.fn.regexFindId = function(re){ return this.filter(function(){ var id = this.id; return id.match(re); }); }; 

EDIT: You can use variables in a regex by simply declaring them as follows:

 var re = new RegExp(myVar); 
+2
source share
  function( tableid, dynamicid, componentid) { a = tableid+dynamicid ; $( " [id^="+a+"][id$="+componentid+"] "). each(function() { // do ur stuff } ); } 
+1
source share

All Articles