Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find complete id using partial ID in jQuery

Tags:

html

jquery

I am stuck in situation where i need to find complete id using partial id in jQuery. Suppose i have below HTML element

       <div id="Partial_Known_Id">
          <span>
          </span>
       </div>

How do i fetch full id of above element using partial id?

Suppose i know that it begins with Partial_. I have tried below

var b = $('[id*="Partial_"]');

But it does not seem to work.

Anyway i can get full id in some variable??

like image 519
Richa Avatar asked Sep 29 '22 04:09

Richa


1 Answers

If you want to know all of their ids, you'll need a loop, e.g.:

var b = $('[id*="Partial_"]');
b.each(function() {
    console.log(this.id);
});

That loop can be in your code (as above), or in jQuery's code:

var ids = $('[id*="Partial_"]').map(function() { return this.id; }).get();

That latter gives you an array of the matching ids.

Note that if you know the id starts with "Partial_", you can use ^= rather than *=. *= will match the string anywhere; ^= will only match it at the beginning of the id.

Live example of both each and map:

var b = $('[id*="Partial_"]');
snippet.log(b.length + " found using `*=`:");
b.each(function() {
  snippet.log(this.id);
});

snippet.log("As an array: " + b.map(function() {
  return this.id;
}).get().join(", "));

snippet.log("---");

b = $('[id^="Partial_"]');
snippet.log(b.length + " found using `^=`:");
b.each(function() {
  snippet.log(this.id);
});

snippet.log("As an array: " + b.map(function() {
  return this.id;
}).get().join(", "));
<div id="Partial_1"></div>
<div id="Partial_2"></div>
<div id="Partial_3"></div>
<div id="blah_Partial_foo"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
like image 119
T.J. Crowder Avatar answered Oct 13 '22 00:10

T.J. Crowder