skip to Main Content

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?

2

Answers


  1. 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]`);
    
    Login or Signup to reply.
  2. You can chain multiple finds with .end()

    $cotainer
      .find("selector")
      .end()
      .find("selector")
      .end()
    
    /*
    wpforms-22603
    -field_17
    data-field-id="17"
    wpforms-field-likert_scale
    */
    $(document).ready(function () {
      var $matchMe = function ($cotainer, formId, fieldId) {
        return $cotainer
          .find("[id^='wpforms-" + formId + "']")
          .end()
          .find("[class*='-field_" + fieldId + "']")
          .end()
          .find('[data-field-id="' + fieldId + '"]')
          .end()
          .find(".wpforms-field-likert_scale")
          .end()
      }
      console.log($matchMe($("#container")).length)
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <div id="container">
      <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"
      />
      <div
        id="wpforms-22603-field_19-container"
        class="wpforms-field wpforms-field-likert_scaleX"
        data-field-id="19"
      />
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search