jqueryjquery-selectors

jQuery match element by id and class


I need to catch some elements in a form. The elements look like this:

<div id="wpforms-22603-field_17-container" class="wpforms-field wpforms-field-likert_scale" data-field-id="17">
<div id="wpforms-22603-field_18-container" class="wpforms-field wpforms-field-likert_scale" data-field-id="18">
<div id="wpforms-22603-field_19-container" class="wpforms-field wpforms-field-likert_scale" data-field-id="19">

The variable part is the number after -field_ and of course the data-field-id value itself.

So I wrote this:

var elem = $(this).closest('[id^=wpforms-'+this_form_id+'-field_][id$=-container]');

where this_form_id contains the value 22603. This works well, but I need to also specify a class in the matching process, and that class is wpforms-field-likert_scale.

So I tried this:

var elem = $(this).closest('[id^=wpforms-'+this_form_id+'-field_][id$=-container] .wpforms-field-likert_scale');

which doesn't work. What am I doing wrong?


Solution

  • Remove the space before the .

    var elem = $(this)
      .closest(`[id^=wpforms-${this_form_id}-field_][id$=-container].wpforms-field-likert_scale`);
    

    Alternatively use filter

    var elem = $(this).closest('.wpforms-field-likert_scale')
      .filter(`[id^=wpforms-${this_form_id}-field_][id$=-container]`);
    

    const this_form_id = '22603';
    $('button').on('click', function() {
      var elem = $(this).closest('.wpforms-field-likert_scale')
        .filter(`[id^=wpforms-${this_form_id}-field_][id$=-container]`);
        console.log(elem.attr('id'))
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div id="wpforms-22603-field_17-container" class="wpforms-field wpforms-field-likert_scale" data-field-id="17"><button>Click</button></div>
    <div id="wpforms-22603-field_18-container" class="wpforms-field wpforms-field-likert_scale" data-field-id="18"><button>Click</button></div>
    <div id="wpforms-22603-field_19-container" class="wpforms-field wpforms-field-likert_scale" data-field-id="19"><button>Click</button></div>