Lory Lory Lory Lory - 1 year ago 60
jQuery Question

jQuery: how to match final parts of ids

In order to open popup with some content, I have many tag anchors whose ids start with "poc" like poc1, poc2, poc3...
At the same way, I have the same number of tag div whose ids start with "pop" like pop1, pop2, pop3... How can I match them in jQuery so that
poc1 --> pop1
poc2 --> pop2
I'm writing something like

jQuery("a[id^='poc']").click(function() {

but instead of "pop1" I need the correspondent pop according to the final value of poc. Is it possible?

Answer Source

Get the specific number by replacing the string poc from the clicked element's id:

jQuery("a[id^='poc']").click(function() {
    var num = $(this).attr('id').replace('poc','');
    jQuery('#pop' + num).bPopup();


Click on each of the poc elements and the respective pop element will get red

$('[id^=poc]').on('click', function() {
  var num = $(this).attr('id').replace('poc','');
  $('#pop' + num).css({'color':'red'});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="poc1">poc1</span>
<span id="poc2">poc2</span>
<span id="poc3">poc3</span>
<span id="pop1">pop1</span>
<span id="pop2">pop2</span>
<span id="pop3">pop3</span>