How to find the previous sibling of parent

10,798

Solution 1

$('.myTest').parent().prev('dt').text();

Solution 2

use .closest()

$('.myTest').closest('dd').prev('dt').text();
Share:
10,798
silvster27
Author by

silvster27

Updated on June 17, 2022

Comments

  • silvster27
    silvster27 almost 2 years

    Okay, I know this should be simple. I have a definition list (<dl>) that contains data definitions and data labels. I have an input in one of the data definitions so a user can define the definition.

    I am then trying to get the name of the label for that definition. In the demo the alert should prompt with "cycle_3".

    var myErrors = $('.myTest').prev('dt').text();
    console.log(myErrors);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <dl>
      <dt> cycle_1:</dt>
      <dd> test </dd>
      <dt> cycle_2: </dt>
      <dd> test </dd>
      <dt> cycle_3: </dt>
      <dd>
        <input class="myTest" value="test" />
      </dd>
    </dl>