JSFiddle - React, Tailwind, and code Playground

by Ying Chor Ding

HTML

<div id="banana" class="fruit">
    <div>
      <p>
        some text
      </p>
    </div>
  </div>
  <div id="apple" class="fruit">
    <div>
      <p id="test">
        some text
      </p>
    </div>
  </div>
  <div id="cherry" class="fruit">
    <div>
      <p>
        some text
      </p>
    </div>
  </div>

JavaScript

// you're running a query starting from the window (this) and looking up for more elements - but window has no parents.
  // var id = jQuery( this ).closest( ".fruit" ).attr( "id" );
  // so here id is undefined
  // jQuery( 'p#test' ).append( id );
 
  // try this instead... ($ is jQuery)
  
  // wait for the DOM to be ready first
  $(function () {
    // get your test element
    var testElement = $('p#test');
    // look for the fruit parent
    var parentFruit = testElement.closest('.fruit');
    // if you find one
    if (parentFruit.size()) {
      // write it's id to your element
      testElement.append(parentFruit.attr('id'));
    }
  });