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??
If you want to know all of their id
s, 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 id
s.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With