Find full id using partial id in jQuery

I am stuck in a situation where I need to find the full id using partial id in jQuery. Suppose I have an HTML element

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

How to get the full id of an element above using a partial id?

Suppose I know that it starts with Partial _ . I tried below

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

But that does not work.

Anyway, can I get the full id in some variable ??

+4
source share
3 answers

If you want to know all your ids, you need a loop, for example:

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

This loop can be in your code (as indicated above) or in jQuery code:

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

id s.

, , id "Partial_", ​​ ^=, *=. *= ; ^= id.

each, 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.imtqy.com/simple-snippets-console/snippet.js"></script>
Hide result
+4

.attr():

var b = $('[id^="Partial_"]').attr('id');

* , ^, .

0

You are using the wrong selector.

var b = $('[id^="Partial_"]').attr('id');

See the documentation for more information .

-1
source

Source: https://habr.com/ru/post/1584228/


All Articles